API Wrapper

Define and Call your restful APIs like a function.
This package is based on @single9/api-tester but use Axios instead of Request.
Installation
npm i @single9/api-wrapper
Usage
const ApiWrapper = require('@single9/api-wrapper');
Create
const api = new ApiWrapper([
{
name: '<Api Name>',
path: '<Api Path>',
method: '<HTTP Method>',
},
], {
configureAxios(axios){
},
baseUrl: '<Base URL of API>',
headers: {
},
auth: {
username: 'username',
password: 'password',
}
})
Factory baseUrl
You can use factory function to dynamically set the base URL. This is useful if your host domain is
a SRV record.
Example
const api = new ApiWrapper([
{
name: '<Api Name>',
path: '<Api Path>',
method: '<HTTP Method>',
},
], {
baseUrl: async () => resolveSRV(process.env.API_HOST),
});
Use
api.<api_name>(params)
- api: Your
ApiWrapper instance.
- api_name: The name of the API that you set before.
- params: Compatible with axios request config
Params
params.queryString
Used for query string. e.g. /users?limit=100
api.test({
queryString: {
key: value
}
})
api.test({
queryString: [
{
name: string,
value: string | number,
}
]
})
params.pathParams
Used for path parameters. e.g. /user/:id
api.test({
pathParams: {
key: value
}
})
api.test({
pathParams: [
{
name: string,
value: string | number,
}
]
})
Example
const ApiWrapper = require('@single9/api-wrapper');
const schema = [
{
name: 'newPost',
path: '/posts',
method: 'post',
},
{
name: 'getTodo',
path: '/todos/:todoId',
method: 'get',
},
];
const api = new ApiWrapper(schema, {
configureAxios(item){
item.interceptors.request.use(
(request) => { console.log('url: %s , req: %o', request.url); return request; },
)
item.interceptors.response.use(
(response) => { console.log('url: %s , res: %o', response.url, response.data); return response; },
)
},
baseUrl: 'https://jsonplaceholder.typicode.com',
});
async function start() {
try {
const post = await api.newPost({
data: {
title: 'foo!!!!!!',
body: 'bar!!',
userId: 1
},
});
console.log(post.data);
const get = await api.getTodo({
pathParams: {
todoId: 2,
},
});
console.log(get.data);
} catch (err) {
console.error(err);
}
}
start();