data-fetcher
This is a simple and powerful promise based wrapper around native fetch
or node-fetch
for node.js
Usage
Simple GET request
Custom method
Defaults
console // baseUrl:'' args: mode:'cors' credentials:'same-origin' headers: Accept:'application/json' 'Content-Type':'application/json'
You can customize any property of config, for example ...
index.js
- endpoint of you app
defaultsbaseUrl = 'http://example.com'
Then deep in the app
Custom headers
Or you can set it globaly. All that you need just modify your login method
Just for example
const login = async { const token = defaultsargsheadersAuthorization = `Bearer `}
Then you can send anywhere request in your app securely :)
This way you can add any properties to the defaults.args that will be passed to fetch() as second argument or add it individually to fetcher() as second argument too
onFail handler
if your token might be die after some time probably you will want to update it. It is do this way
./src/storage.js
const localStorage = window const setToken = { localStorage defaultsargsheadersAuthorization = token ? `Bearer ` : undefined} const setRefreshToken = { localStorage} const getToken = localStorage const getRefreshToken = localStorage
./src/index.js
defaultsbaseUrl = 'http://example.com'defaultsonFail = async { const refreshToken = if refreshToken && edatastatus === 401 // only for 401 http status code but you can customize it for you const token: newToken refreshToken: newRefreshToken = await // false, won't run error handler `onFail` if request is fail. // default true return throw e}
Then if one of your requests crashed with 401 status code and you have a refresh token will send request to update token and setup newToken and newRefreshToken and most important request which was crashed will resend again with new credentials. It will look like your request was sended without any troubles
Package contents
As you have seen you can also just import default export from package.
API
fetcher(url, options, catchError)
Parameters
url
- (string) an url to remote server
options
- (object)
options = {
baseUrl: string // default ''
method: string // default 'get'
body: object | string // default ''
query: object | string // default ''
withData: bool // default false
type: string (json|formData) // default json
headers: object | bool // default false
}
catchError
- (bool) true - should catch errors and handle it only if onFail is specified it will be actual
Fetcher
- class of fetcher to use in server-side application
stringifyQuery
- will stringify an object to a string
parseQuery
- will parse a string that was stringified to an object