// 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 });
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
stringorobject
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.