Loading repository data…
Loading repository data…
Amareis / repository
Simple pure TypeScript REST API client that makes your code lesser and more beautiful than without it.
= another-rest-client
Simple REST API client that makes your code lesser and more beautiful than without it.
There is some rest clients - https://github.com/marmelab/restful.js[restful.js], https://github.com/cujojs/rest[cujojs/rest] or https://github.com/lincolnloop/amygdala[amygdala] - so why you need another rest client? First, because all of this is not maintained anymore :) But also, because with it your code less and more beautiful than without it or with any analogs. Also, its code really simple - less than 300 sloc and (almost) without magic, so you can just read it (and fix, may be?) if something go wrong.
To prove my words, here is an minimal working code (you can explore more examples https://github.com/Amareis/another-rest-client/tree/master/examples[here]):
And it works with typescript!
import {RestClient} from 'another-rest-client'
const api = new RestClient('https://api.github.com').withRes({ repos: 'releases', } as const)
== Installation
Library is available with npm:
npm install another-rest-client
Now, add it in script tag or require it or import it:
ATTENTION: If you want to use another-rest-client with node.js, you must define XMLHttpRequest before import (https://github.com/driverdan/node-XMLHttpRequest[see here]):
== Usage
And here we go! First, let's define resources, using res method:
Now we can query our resources using methods get (optionally gets query args), post, put, patch (gets body content) and delete. All these methods returns promise, that resolves with object that given by server or rejects with XMLHttpRequest instance:
api.cookies.get() //GET https://example.com/cookies api.cookies.get({fresh: true}) //GET https://example.com/cookies?fresh=true api.cookies.get({'filter[]': 'fresh'}, {'filter[]': 'taste'}) //GET https://example.com/cookies?filter%5B%5D=fresh&filter%5B%5D=taste
If you want query single resource instance, just pass it id into resource:
api.cookies(42).get() //GET https://example.com/cookies/42
//GET https://example.com/cookies/42?fields=ingridients,baker api.cookies(42).get({fields: ['ingridients', 'baker']})
You can query subresources easily:
api.dogs(1337).toys.get() //GET https://example.com/dogs/1337/toys api.dogs(1337).friends(2).delete() //DELETE https://example.com/dogs/1337/friends/2
You can use url resource method to get resource url:
And, of course, you always can use ES6 async/await to make your code more readable:
== TypeScript
Library infer types from schema, passed to res. But it returns new resource (or array or object), so to use it
correctly, you need to use withRes method, which returns modified original resource:
let api = new RestClient('https://api.github.com').withRes({ repos: 'releases', } as const) // as const needed to infer resources names
You can then add more resources reusing already typed resource:
Custom shortcuts currently not working with TypeScript! And shorcuts always will be in typings, even if they are disabled.
== Events
RestClient use https://github.com/allouis/minivents[minivents] and emit some events:
request - when open XMLHttpRequest, but before send.response - when get server response.success - when get server response with status 200, 201 or 204.error - when get server response with another status.All events gets current XMLHttpRequest instance.
Often use case - authorization:
Also, returns by get, post, put, patch and delete Promise objects also emit these events, but only for current request.
You can use events to set responseType XMLHttpRequest property, to handle binary files (and you can compose it with custom decoders, as described below, to automatically convert blob to File object):
== Configuration
All the examples given above are based on the default settings. If for some reason you are not satisfied, read this section.
All configuration is done using the object passed to the constructor or method conf. Some options are also duplicated by optional methods arguments.
conf returns full options. If you call it without parameters (just conf()), it gives you current options.
If you want change RestClient host (lol why?..), you can just:
=== Trailing symbol
Some APIs require trailing slash (for example, this is the default behavior in the django-rest-framework). By default another-rest-client doesn't use any trailing symbol, but you can change this:
Of course, you can pass all you want ({trailing: '/i-have-no-idea-why-you-want-this-but-you-can/'}).
=== Shortcuts
Shortcuts - resources and subresources, that accessible as parent resource field:
By default, another-rest-client will make shortcuts for defined resources. This behavior can be disabled in three ways:
api.sounds === undefined
//first way const api = new RestClient('https://example.com', {shortcut: false}) //or, second way api.conf({shortcut: false}) //or, third way const sounds = api.res('sounds', false)
First two ways disables shortcuts globally - on all resources and subresources. Third way disables shortcuts locally - in one res call. Also, with third way you can locally enable shortcuts (pass true as second res argument) when globally they are disabled.
Local disable of shortcuts can solve some name conflicts (when resource shortcut overwrites some method), but, probably, you will not be affected by this.
It is strongly recommended do not disable the shortcuts, they greatly enhance code readability.
You can also add custom shortcuts for resources via rules. Those can be configured via the shortcutRules array in the options. When a resource is added all rules will be invoked with the resource name as argument. If the return value is a non-empty string, it will serve as an additional shortcut.
Have a look at this example which will convert strings with dashes into their camel-case counterpart to serve as additional shortcut:
const DASH_REG = /(-)(.)/g function dashReplace(resourceName) { return resourceName.replace(DASH_REG, (match, p1, p2) => p2.toUpperCase()) }
=== Request content type
When you call post, put or patch, you pass an object to be encoded into string and sent to the server. But how it will be encoded and what Content-Type header will be set?
By default - in json (application/json), using JSON.stringify. To change this behavior, you can manually set request content type:
By default RestClient can encode data in application/json and application/x-www-form-urlencoded. You can add (or replace defaults with) your own encoders:
If there is no suitable encoder, passed object will be passed to the XMLHttpRequest.send without changes.
=== Response content type
When server answers, it give Content-Type header. another-rest-client smart enough to parse it and decode XMLHttpRequest.responseText into object. By default it can decode only application/json using JSON.parse, but you can add your own decoders:
If there is no suitable decoder (or server given't Content-Type header), gotten XMLHttpRequest.response will