@vkhalikov/rest-api-client
v0.3.1
Published
A basic, extendable REST API Client
Downloads
4
Readme
REST API Client
A basic, extendable client for your REST API.
Installation
npm install --save @vkhalikov/rest-api-client
Basic usage
// resources/todos.js
import { Resource } from '@vkhalikov/rest-api-client';
export const todos = new Resource('todos');
// api.js
import Client from '@vkhalikov/rest-api-client';
import { todos, posts, users } from './resources';
const API_URL = 'https://api.mysite.com';
const resources = [todos, posts];
const api = new Client(API_URL, { resources });
api.route('rest/v2', { resources: [users] });
export default api;
// app.js
import api from './api.js';
let todos;
// final url: "https://api.mysite.com/todos"
api.todos.getAll()
.then((data) => {
todos = data;
})
.catch((err) => {
handleError(err);
});
// You don't have to worry about serialization
// Request body will be automatically serialized with JSON.parse(),
// if 'Content-Type' header contains 'json', which is a default header
const newPost = {
title: 'Amazing Post',
message: 'Hello, Worm!',
};
// final url: "https://api.mysite.com/posts"
api.posts.create({ body: newPost });
// final url: "https://api.mysite.com/rest/v2/users/001"
api.users.getById(001);
let adminPosts;
// final url: "https://api.mysite.com/posts/?userId=001"
api.posts.get({ query: { userId: 001 } })
.then((data) => adminPosts = data)
.catch((err) => {
handleError(err);
});
// You can also make requests directly
api.post('posts', { body: newPost });
API
Client
constructor(baseURL, { resources, authToken, defaultFetchOptions, bodyParser, onError }): Client
Arguments
| Argument | Required | Type | Default Value | Description |
|:---------------------:|:--------:|:-------------------------------------------------------------------:|:----------------------------------------:|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| baseURL
| ✔ | string
| undefined
| URL of your API. |
| resources
| | [Resource]
| []
| An array of Resources. Each resource becomes an Client instance property. Example: Resource with name
"todos"
will be available as api.todos
property. |
| authToken
| | AuthToken
| undefined
| An instance of AuthToken
. For more detailed information see AuthToken
|
| defaultFetchOptions
| | object
| { 'Content-Type': 'application/json' }
| Will be added to fetch options with every request. |
| bodyParser
| | string
or
function(body: Body, requestMethod:string): Promise
| (body) => body.json()
| A function that will return a parsed body depending on a requestMethod. If a string is passed, one of predefined body parsers will be used. Valid string options: json
, arrayBuffer
, blob
, text
, formData
. |
| onError
| | function(error): void
| undefined
| A function that will handle response errors if Response.ok === false
. Pass it if you want to specify your own error types depending on response statuses or another information that your API provides, or maybe you want to handle them in one place. |
Methods
A basic methods, which are you used to create requests with according HTTP methods.
You can use them for a specific calls to your API, or if you don't need any Resources
.
get(path, options): Promise
post(path, options): Promise
patch(path, options): Promise
put(path, options): Promise
delete(path, options): Promise
Arguments
| Argument | Required | Type | Default Value | Description |
|:---------------------:|:--------:|:----------------------:|:-------------:|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| path
| ✔ | string
| undefined
| A path to a resource. The result URL will be {baseURL}/{path}?{query}
. |
| options.query
| | string
or
object
| undefined
| Passing this option will result in adding the query
part to the final URL. If string
it will be passed as is. If object
it will be stringified using query-string
. |
| options: {...rest}
| | | {}
| Rest options are considered fetch()
options. |
route(path: String, options): void
Arguments
| Argument | Required | Type | Default Value | Description |
|:---------------------:|:--------:|:---------------------:|:--------------:|--------------------------------------------------------------------------------------------------------|
| path
| ✔ | string
| undefined
| A path to a group of resources. All resources passed to this route will be sending requests to a specified path. |
| resources
| | [Resource]
| []
| Same as for Client
|
setAuthToken(authToken: AuthToken): void
Arguments
| Argument | Required | Type | Default Value | Description |
|:-----------:|:--------:|:-----------:|:-------------:|--------------------------------------------------------------------------------------------------------|
| authToken
| ✔ | AuthToken
| undefined
| An instance of AuthToken
. Will be passed in Authorization
header with every request. | |
resetAuthToken(): void
Sets authToken to null
injectResources(resources: [Resource]): void
Manual resource injection.
Arguments
| Argument | Required | Type | Default Value | Description |
|:-----------:|:--------:|:------------:|:-------------:|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| resources
| ✔ | [Resource]
| undefined
| An array of Resources
. Each resource becomes an Client instance property. Example: Resource with name
"todos"
will be available as api.todos
property. | |
Resource
constructor(name, { defaultFetchOptions, bodyParser }): Resource
| Argument | Required | Type | Default Value | Description |
|:---------------------:|:--------:|:-------------------------------------------------------------------:|:-------------:|------------------------------------------------------------------------------------------------------------------------------------------------|
| name
| ✔ | string
| undefined
| A name of Resource. This defines a name by which a Resource will be available after injection. A name also becomes a path
for every request. |
| defaultFetchOptions
| | object
| undefined
| Same as Client.defaultFetchOptions
and will be merged with them but takes precedence. |
| bodyParser
| | string
or
function(requestMethod:string, body: Body): Promise
| undefined
| Same as Client.bodyParser
. If passed, will be used instead of Client.bodyParser
for this Resource. |
| path
| | string
| undefined
| A path to a resource. Overwrites the default path resolution behaviour (by a resource name). |
Methods
get({ id, query, ...fetchOptions }): Promise
getById(id, { query, ...fetchOptions }): Promise
getAll({ query, ...fetchOptions }): Promise
create({ body, ...fetchOptions }): Promise
update({ id, query, body, ...fetchOptions }): Promise
replace({ id, query, body, ...fetchOptions }): Promise
delete({ id, query, ...fetchOptions }): Promise
Arguments
| Argument | Required | Type | Default Value | Description |
|:--------------:|:--------:|:----------------------:|:-------------:|-----------------------------------------------------------------------------------------------|
| id
| | string
| undefined
| An ID of a requested resource. Will be added to a final URL: {baseURL}/{resourceName}/{id}
. |
| query
| | string
or
object
| undefined
| Same as for Client
requests. |
| body
| ✔ | any
valid body type | undefined
| A request body. Examples: string
, formData
, blob
, etc. |
| fetchOptions
| | object
| undefined
| Same as Resource.defaultFetchOptions
and will be merged with them but takes precedence. |
AuthToken
Used in Client
. Will be passed in Authorization
header with every request.
Example: AuthToken with authScheme
Basic
and body
Base64EncodedToken
will become Authorization: Basic Base64EncodedToken
header.
constructor(body, { authScheme }): AuthToken
Arguments
| Argument | Required | Type | Default Value | Description |
|:--------------:|:--------:|:---------------------:|:-------------:|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| body
| | string
| undefined
| A token body. Usually base64 encoded. |
| authScheme
| | string
| Basic
| An auth scheme. For more detalied information see IANA list of authentication schemes. |