0.3.1 • Published 3 years ago

@vkhalikov/rest-api-client v0.3.1

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

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
ArgumentRequiredTypeDefault ValueDescription
baseURLstringundefinedURL 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.
authTokenAuthTokenundefinedAn instance of AuthToken. For more detailed information see AuthToken
defaultFetchOptionsobject{ 'Content-Type': 'application/json' }Will be added to fetch options with every request.
bodyParserstring 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.
onErrorfunction(error): voidundefinedA 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
ArgumentRequiredTypeDefault ValueDescription
pathstringundefinedA path to a resource. The result URL will be {baseURL}/{path}?{query}.
options.querystring or objectundefinedPassing 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
ArgumentRequiredTypeDefault ValueDescription
pathstringundefinedA 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
ArgumentRequiredTypeDefault ValueDescription
authTokenAuthTokenundefinedAn 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
ArgumentRequiredTypeDefault ValueDescription
resources[Resource]undefinedAn 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
ArgumentRequiredTypeDefault ValueDescription
namestringundefinedA 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.
defaultFetchOptionsobjectundefinedSame as Client.defaultFetchOptions and will be merged with them but takes precedence.
bodyParserstring or function(requestMethod:string, body: Body): PromiseundefinedSame as Client.bodyParser. If passed, will be used instead of Client.bodyParser for this Resource.
pathstringundefinedA 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
ArgumentRequiredTypeDefault ValueDescription
idstringundefinedAn ID of a requested resource. Will be added to a final URL: {baseURL}/{resourceName}/{id}.
querystring or objectundefinedSame as for Client requests.
bodyany valid body typeundefinedA request body. Examples: string, formData, blob, etc.
fetchOptionsobjectundefinedSame 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
ArgumentRequiredTypeDefault ValueDescription
bodystringundefinedA token body. Usually base64 encoded.
authSchemestringBasicAn auth scheme. For more detalied information see IANA list of authentication schemes.

0.3.1

3 years ago

0.3.0

3 years ago

0.2.1

3 years ago

0.2.0

3 years ago

0.1.0

3 years ago