Fetch builder
Lightweight and extremely customizable alternative to superagent, request, axios, frisbee.
RequestOptions builder toolkit for whatwg-fetch. Easily create or extend custom fetcher options.
Features:
- Immutable
- Customizable and extendable options
- Placeholders in urls, custom params serializer and placeholder mapper
- Headers merging
- Composable postProcess handler
Fetcher
// @flow // Fetcher with some defaultsconst baseFetcher: Fetcher<any any> = baseUrl: '/api' headers: 'Accept-Language': 'ru' method: 'GET' // throws HttpError if fetch status not in range 200-300 postProcess: checkStatus serializeParams: // Get json from responseconst jsonFetcher: Fetcher<any any> = baseFetcher type User = id: string; name: string; // fetch userconst userPromise: Promise<User> = jsonFetcher// GET /api/user/1 // Or create custom user fetcher with placeholder as idconst userFetcher: Fetcher<User id: string q: string> = jsonFetcher userFetcher// GET /api/user/1?q=2 type Session = isLogged: boolean; const sessionFetcher: Fetcher<Session void> = jsonFetcher sessionFetcher// GET /api/session const delSessionFetcher: Fetcher<Session void> = sessionFetcher delSessionFetcher// DELETE /api/session // Set default credentialsconst authUserFetcher: Fetcher<User id: string> = userFetcher authUserFetcher/*GET /api/user/1headers: { 'Accept-Language': 'ru', 'Auth': 'Token bla-bla'}*/ authUserFetcher/*POST /api/user/1body: {id: 1, name: 'test'}headers: { 'Accept-Language': 'ru', 'Auth': 'Token bla-bla'}*/
Loader
Loader is cached wrapper around Fetcher.
// @flow // ...const loader = sessionFetcher loader // Calls Fetcher once, fetch result is cached:loader // Reset loaderloader
Repository
Repository caches Loaders by key. Key - is string, builded from sorted FetcherRec.params values.
// @flow // ...const repository = authUserFetcher // New fetch:repository // params.id is changed: new fetch:repository // From cache:repository // From cache:repository // Reset user 1:repository // Reset allrepository
Custom cache key getter:
// @flow: string { const params: id: string: string = recparams || {} return Object} const repository = authUserFetcher myGetkey
Interface of Fetcher constructor
= Promise<IFetcher<Result Params>>