Abstractions on-top of
superagent
(or other Ajax libaries) for communication with REST. Targeted mostly againstDRF
running onDjango
so some logic might not be applicable for other frameworks.
npm i tg-resources
import Resource from "tg-resources"
const onLoad = result => console.log(result);
const onError = result => console.error(result);
// Do a get request to /path/to/api?foo=bar
new Resource('/path/to/api').fetch(null, {foo: 'bar'}).then(onLoad).catch(onError);
// Do a post request to /path/to/api?foo=bar with data: {'asd':'sdf'}
new Resource('/path/to/api').post(null, {asd: 'sdf'}, {foo: 'bar'}).then(onLoad).catch(onError);
// Do a patch request to /path/to/api?foo=bar with data: {'asd':'sdf'}
new Resource('/path/to/api').patch(null, {asd: 'sdf'}, {foo: 'bar'}).then(onLoad).catch(onError);
// Do a put request to /path/to/api?foo=bar with data: {'asd':'sdf'}
new Resource('/path/to/api').put(null, {asd: 'sdf'}, {foo: 'bar'}).then(onLoad).catch(onError);
// Do a delete request to /path/to/api?foo=bar with data: {'asd':'sdf'}
new Resource('/path/to/api').del(null, {asd: 'sdf'}, {foo: 'bar'}).then(onLoad).catch(onError);
Construct a new resource for loading data from a single (or dynamic) endpoint
apiEndpoint
(string): Api url used for this resource. Supports ES6 token syntax, e.g: "/foo/bar/${pk}"[expectedStatus=[200, 201]]
(Array): Valid response codes[mutateResponse=null]
(Function): Optional function for mutating the response before it's sent back to the user. Signature:response => response
The Resource module also supports dynamic urls by supporting ES6 token syntax. Request methods
can then provide values as an object using the first argument kwargs
.
So for example:
new Resource('/foo/bar/${pk}').get({pk: 1}).then(x => x);
Would result in a GET request to /foo/bar/1
(Resource): Returns instance of Resource
.
Do a get request to the resource endpoint with optional kwargs and query parameters.
kwargs={}
(Object): Object containing the replacement values if the resource uses tokenized urlsquery={}
(Object|string): Query parameters to use when doing the request.
(Promise): Returns a Promise
that resolves to the remote result or throws if errors occur.
Do a method
request to the resource endpoint with optional kwargs and query parameters.
kwargs={}
(Object): Object containing the replacement values if the resource uses tokenized urlsdata={}
(Object|string): Query parameters to use when doing the request.query={}
(Object|string): Query parameters to use when doing the request.method='post'
(string): Lowercase name of the HTTP method that will be used for this request.
(Promise): Returns a Promise
that resolves to the remote result or throws if errors occur.
Alias for Resource.post(kwargs, data, query, 'patch')
Alias for Resource.post(kwargs, data, query, 'put')
Alias for Resource.post(kwargs, data, query, 'del')
MIT © Thorgate