# Fetch API wrapper resource
Composable fetch API interface. Based on Fetch API.
# Installation
yarn add @aspectus/resource
# Usage
Sometimes you need an API call. This library will help you to made those requests declarative and more easily configurable.
# Simple chaining
import {
ResourceChain,
baseResource,
receiveResource,
sendResource
} from '@aspectus/resource';
// Is the same as imported: baseResource
const resource = new ResourceChain()
.config({
mode: 'same-origin',
cache: 'default',
credentials: 'same-origin',
redirect: 'follow',
referrer: 'client',
});
// Is the same as imported: receiveResource
const resourceGET = resource
.config({
method: 'GET',
});
// Is the same as imported: sendResource
const resourcePOST = resource
.config({
method: 'POST',
});
Each time you execute method - new chain creates. The old one stays unchanged.
# Middleware usage
import {
sendResource,
jsonRequestMiddleware,
headersMiddleware,
overrideMiddleware
} from '@aspectus/resource';
// Now request will transform body to JSON and will be sent
// with header Content-Type: application/json
const resource = sendResource
.middleware(jsonRequestMiddleware);
const textJsonMiddleware = headersMiddleware(overrideMiddleware({
'Content-Type': 'text/json',
}));
// This middleware will change Content-Type header.
const otherContentType = resource
.middleware(textJsonMiddleware);
// Middleware may have `order` property.
// It's value must be from 0-1000. Default is 500.
// Using it you may control the execution order of the middleware.
//
// This request will have header Content-Type: application/json because
// of the provided middleware execution order is lower than
// `jsonRequestMiddleware` has.
const otherContentType = resource
.middleware(textJsonMiddleware, 400);
# Custom fetcher
By default - resource will use fetch
function to make requests. But you may change that behavior by providing custom Fetch API implementation. Or just your own wrapper over fetch
.
import { receiveResource } from '@aspectus/resource';
const resource = receiveResource
.fetcher(yourCustomFetchAPIImplementation);
const cachedResource = resource
.fetcher(cachableFetch);
# Url getter
Resource chain mechanism is assuming that you have a dynamically generated URL based of the provided parameters. So it has a method to change internal urlGetter
.
import { receiveResource } from '@aspectus/resource';
import { always } from 'ramda';
import * as qs from 'querystring';
// `always` function from `ramda` creates function that will always return
// passed initially value. So in this case resource always will be requesting
// google.com.
const resource = receiveResource
.url(always('http://google.com'));
const dynamicUrlGetter = receiveResource
.url(parameters => `/some/url/with/dynamic/get/parameters/?${qs.stringify(parameters)}`);
# Usage
import { resource, dynamicUrlGetter } from 'your/resource/path.js'
resource.execute()
dynamicUrlGetter.execute({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })