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
For react-native please use tg-resources-react-native
which does not depend on babel-runtime.
see the Changelog
import Router, { Resource } from "tg-resources"
const onLoad = result => console.log(result);
const onError = result => console.error(result);
const api = new Router({
cats: new Resource('/cats'),
cat: new Resource('/cats/${pk}')
}, {
apiRoot: '/api/v1' // Set api root
});
// Do a get request to /api/v1/cats?gender=M
api.cats.fetch(null, {gender: 'M'}).then(onLoad, onError);
// Do a head request to /api/v1/cats?gender=M
api.cats.head(null, {gender: 'M'}).then(onLoad, onError);
// Do a post request to /api/v1/cats with data: {name: 'Twinky', gender: 'M'}
api.cats.post(null, null, {name: 'Twinky', gender: 'M'}).then(onLoad, onError);
// Do a patch request to /api/v1/cats/1 with data: {name: 'Tinkelberg'}
api.cat.patch({pk: 1}, null, {name: 'Tinkelberg'}).then(onLoad, onError);
// Do a put request to /api/v1/cats with data: {pk: 1, name: 'Twinky'}
api.cats.put(null, null, {pk: 1, name: 'Twinky', gender: 'M'}).then(onLoad, onError);
// Do a delete request to /api/v1/cats/1 with data: {'free':'yes'}
api.cat.del({pk: 1}, null, {free: 'yes'}).then(onLoad, onError);
Please note that the router is useful for providing default configuration and grouping endpoints. It's still possible to use Resources without a router(see Resource api)
apiRoot
(String): Base for all resource pathsheaders
(Object|Function: Object): Optional Function or Object which can be used to add any additional headers to requests.cookies
(Object|Function): Optional Function or Object which can be used to add any additional cookies to requests. Please note that in modern browsers this is disabled due to security concerns.mutateResponse
(Function): Optional function with signatureresponse => response
which can be used to mutate response before resolving it.statusSuccess
(Array[int]): Array (or a single value) of status codes to treat as a success. Default: [200, 201, 204]statusValidationError
(Array[int]): Array (or a single value) of status codes to treat as ValidationError. Default: [400]defaultHeaders
(Object): Object of headers which should be added to all requests: Default:{ Accept: 'application/json' }
parseErrors
(int): Function used to parse response errors into a ValidationError object. The default handler is built for Django/DRF errors.prepareError
(int): Function used to normalize a single error. The default handler is built for Django/DRF errors.
With tg-resources, all errors are Rejected. The logic is best described with an example:
const resource = new Resource('user/login');
const payload = {
user: 'foo',
passwrod: 'bar'
};
resource.post(null, payload).then(user => {
console.log({
type: 'LOGGED_IN',
data: {
user: user
}
});
}, error => {
// Network error occurred
if (error.isNetworkError) {
console.error({
type: 'NETWORK_FAILED',
data: {
error: error
}
});
} else {
// Validation error occurred (e.g.: wrong credentials)
if (error.isValidationError) {
console.error({
type: 'LOGIN_FAILED',
data: {
message: error.firstError(true),
error: error
}
});
} else {
// As a last resort, also handle invalid response codes
console.error({
type: 'SERVER_ERROR',
data: {
error: error
}
});
}
}
});
Construct a new resource for loading data from a single (or dynamic) endpoint
apiEndpoint
(string): Endpoint used for this resource. Supports ES6 token syntax, e.g: "/foo/bar/${pk}"options
(Object): Object containing options for this resource. see Configuration
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')
Generic base class for all errors that can happen during requests
isNetworkError
(bool): Alwaysfalse
isInvalidResponseCode
(bool): Alwaysfalse
isValidationError
(bool): Alwaysfalse
Error class used for all network related errors
isNetworkError
(bool): Alwaystrue
error
(Error): Original Error object that occured during network transport
Error class used when unexpected response code occurs
isInvalidResponseCode
(bool): Alwaystrue
statusCode
(string): Response status coderesponseText
(int): Response body text
Error class used when backend respons with a errorStatus
. This object can also be extended via
Config.ValidationErrorExtras
.
isInvalidResponseCode
(bool): Alwaysfalse
isValidationError
(bool): Alwaystrue
Get field specific error
fieldName
(string): Field name[allowNonField=false]
(bool): If true, also check for nonFieldErrors if the specified field does not have an error
(any): Returns a normalized error for fieldName
or null
Deprecated alias of getError
Get first error normalized to a string for this ValidationError
[allowNonField=false]
(bool): If true, also check for nonFieldErrors
(any): First error as a string
or null
MIT © Thorgate