Margaret Fetcher
Dead simple request classes for fetch.
Usage
To use it simply create a class that extends JsonRequest
(or AbstractRequest
) and define requests as methods on it.
The AbstractRequest
class comes with a method per HTTP verb (this.get
, this.post
etc.).
; query = include: 'articles' ; { return this; } { return this; } { const body = ; body; return this; }
To then use those methods simply call the class anywhere:
; const user = ;
You can also use the CrudRequest
class which already comes with methods for CRUD endpoints:
; resource = 'users'; query = include: 'articles';
const requests = ; requests;requests;requests;
Advanced usage
Configuring options
You can configure options passed with all requests either as one time thing:
// Merge options with the defaultsUserRequests // Override default optionsUserRequests
Or through the class itself:
{ super; this; }
You can also pass callables as any option, and it will only get resolved before each request. Useful if you need to pass options that need to be always up to date:
UserRequests
Configuring query parameters
You can configure query parameters with the same ease through these provided methods:
// Override all query parametersUserRequests; // Append new query parametersUserRequests ; UserRequests;
You can also pass arrays to these methods:
UserRequests; // ?foo[]=bar&foo[]=baz
Configuring middlewares
The promise returned by fetch
will be passed through a list of middlewares
.
By default it will return an object of the data contained in the response. But you can add your own middlewares to perform specific logic.
; { super; this; } { const authorizationHeader = responseheaders; // Store it somewhere. return response; }
You can disable all middlewares for a given request using the withoutMiddlewares
method:
const users = ;
Extra helpers
The package also comes with some helper methods for common options:
UserRequests
You can use a function as well, like for other options:
UserRequests
Subrequests
Request classes can be nested at will to build more complex paths.
Imagine you have an UserRequests
and an ArticleRequests
, and that an user can have articles, you can do this:
// GET /users/1/articles/2 ;
You can also predefine subrequests through the subrequests
property on a request class:
subrequests = articles: ;
And then retrieve it anytime:
;
Raw fetch requests
Sometimes you just need to bypass everything and do a raw fetch request, you can do that through the fetch
method:
{ const body = ; body; return this; }
Testing
$ npm test$ npm test:watch