Request
Request Client [Fetch]
A lightweight request client with an in-built rest query builder
Installation
npm i @stead/request
yarn add @stead/request
Usage
Given the servers responses are encapsulated as follows:
{
data: "Response goes here..."
}
Setup
import { SteadClient } from '@stead/request'
const client = new SteadClient({
// [Required]
host: 'https://api.example.com',
// [Optional] - for versioned cases
version : 'v1',
// [Optional] - String or Function (can be asynchronous) that returns a string
token: () => 'your_bearer_token',
// [Optional] - Global headers carried with every request
headers: {
'X-STEAD-SRC': 'REQUEST'
},
// [Optional] - Object with the following signature; Functions can also be asynchronous.
storage: {
get: localStorage.getItem,
set: localStorage.setItem,
delete: localStorage.removeItem,
}
});
Sample Requests
Get
Gets the id
, name
and email
of 10 active users.
client.$get('users', {
query: {
select: ['id', 'name', 'email'],
limit: 10,
filter: {
eq: {
active: true
}
}
}
});
// https://api.example.com/v1/users?select=id,name,email&page[limit]=10&filter=eq(active,true)
Users list of 10 should look something like this:
[
{
"id": "091238749082",
"name": "Sample Name",
"email": "sample@email.com"
},
// ...the other 9...
]
Post
Create a new product item and get back it's id
, name
and add in a collection
join.
We could also skip versioning for this request.
client.$post('products', {
name: 'Denim Short',
slug: 'denim_short',
price: 1000,
collection: 'shorts',
tags: ['short', 'denim']
},
{
skipVersion: true,
query: {
select: ['id', 'name'],
include: ['collection']
}
});
// https://api.example.com/products?select=id,name&include=collection
Response should look something like
{
"id": "092370498237",
"name": "Denim Short",
"collection": {
"slug": "shorts"
"name": "Shorts",
"description": "Cool Shorts"
}
}
Put, Patch, Delete
Pretty much the same pattern as the above
Creating a file with PUT
client.$put('files', yourFile, {isFile: true, query: {select: ['name', 'fileType']}})
// https://api.example.com/v1/files?select=name,fileType
Running a PATCH
client.$patch('item/092370498234', yourUpdate, {query: {select: ['name']}})
// https://api.example.com/v1/item/092370498234?select=name
Running a DELETE
client.$delete('files/092370498234', null, {query: {select: ['id', 'name']}})
// https://api.example.com/v1/files/092370498234?select=id,name