Fetch API Call
Awesome fetch api for browser and nodejs with interceptors easy way to declare api endpoints. Provide very easy way to setup api for different backends/services.
Advantages
- Support interceptors
- Support multiple instances wiht its own interceptors
- Easy way to define headers for specific requests
- Declrative api end points
const login = ;; const loadStatistics = ;; const loadUser = ;; // or even bind params to queryconst getUserDetails = ;;
Install
yarn add fetch-api-call
Api Declaration
; const api = ;
Options:
- protocol - http protocol. Available values - http: an https:
- host - server hostname
- headers - requests headers. NOTE that headers could be also set with interceptors
- mode - more details at - https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
- prefix - api url prefix. Useful when there are multiple api versions:
- /user
- /v1/user
- /v2/user
api - function to define api methods in single line of code.
const apiCall = ;
apiCall(params = {}, headers = {}) - function takes two optional params:
- params - api params. Also is used for building final api entrypoint. More detauls see at Api Url Definition and Placeholders.
- headers - certain request headers.
Examples:
// user login apiconst login = ;; // user logout apiconst logout = ;; // get user apiconst getUser = ;;
Interceptors
; const api interceptors = ;
interceptors methods:
- addRequestInterceptor(request)
- addResponseInterceptor(response)
- addErrorInterceptor(error)
Each methods return function to remove interceptor.
Iterceptors will be called for all request done with api.
const login = ;const logout = ; let removeAcessTokenIterceptor = null; const acessToken = await ; removeAcessTokenIterceptor = iterceptors; await ;;
Request Headers
This is useful when using fetch-api-call
on NodeJS. In some cases it is not
possible to use interceptors to set auth headers becasue it will work for all
request. We should specify certain request with certain header.
const getStatistics = ;;
Multiple Api Instances
Very useful if there is microservices backend architecture.
; const Auth = ; const Users = ; const Data = ; const login = Auth; const loadStatisitcs = Data;;
Custom Setup
;; const createApi = ; const api = ; const login = ;
Options:
- headers - default headers
- mode - default mode. More details at - https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
- adapter - default HTTP adapter. See more at - https://tuchk4.github.io/bivrost/docs/adapters.html
- interceptors - initial interceptors. NOTE that this is NOT DEFAULT interceptors.