base-api-client
v1.5.10
Published
Base API client backed by axios
Downloads
1,917
Readme
base-api-client
Base API client backed by axios.
🇺🇦 Help Ukraine
I woke up on my 26th birthday at 5 am from the blows of russian missiles. They attacked the city of Kyiv, where I live, as well as the cities in which my family and friends live. Now my country is a war zone.
We fight for democratic values, freedom, for our future! Once again Ukrainians have to stand against evil, terror, against genocide. The outcome of this war will determine what path human history is taking from now on.
💛💙 Help Ukraine! We need your support! There are dozen ways to help us, just do it!
Table of Contents
Requirements
To use library you need to have node and npm installed in your machine:
- node
>=10
- npm
>=6
Package is continuously tested on darwin, linux and win32 platforms. All active and maintenance LTS node releases are supported.
Installation
To install the library run the following command
npm i --save base-api-client
Usage
Example of telegram client extended from BaseAPI:
import BaseAPI from 'base-api-client';
export default class TelegramAPI extends BaseAPI {
constructor(id, token) {
super(`https://api.telegram.org/${id}:${token}`);
}
message(chatId, html) {
return this.post('sendMessage', {
'parse_mode' : 'HTML',
'text' : html,
'chat_id' : chatId
});
}
file(chatId, fileId) {
return this.post('sendDocument', {
'document' : fileId,
'chat_id' : chatId
});
}
}
Constructor arguments
- url - base URL of the API. Can consist apiPrefix. Will be cast to nodeJS URL object.
- options - object with next attributes:
- timeout - timeout in ms format. Will be cast to integer (in milliseconds). Default: 1m.
- logger - if applied, will add debug and verbose messages before and after each request. Should have next interface:
logger.log(level, object)
.
Methods
HTTP methods:
get(url, params, options)
post(url, data, options)
patch(url, data, options)
put(url, data, options)
delete(url, options)
in all aforementioned methods url
can be both global, or relative to base URL (defined in constructor). params
are url query params, and data
is JSON body. options
are passed directly to axios request
Headers
Implement getHeaders()
method to define select headers for API. Alternativelly, pass headers in options
for each request if headers need behave differently.
Basic auth
use auth
setting, if you want to use basic auth for each request.
this.auth = {
username : '',
password : ''
};
Data processing
Next methods can be used for default data pre/post-processing:
onError(error) {
if (error.isAxiosError) {
throw new API_ERROR(error);
}
throw error;
},
onResponse(res) {
return res.data;
}
Errors
the package exposes API_ERROR
, that can be used outside:
import BaseAPI, { API_ERROR } from 'base-api-client';
class API extends BaseAPI {
constructor() {
super('http://wiwbif.is/fugo');
}
async createUser(email) {
try {
const user = await this.post('/users', { email });
return user.id;
} catch (error) {
if (error instanceof API_ERROR) {
console.log('raw http error:', error.payload);
throw error;
}
}
}
}
Logging and Tracing
You can pass logger while api creation, but also this can be done by calling initLogger(logger)
method directly.
Alternatively, use polymorphism and implement the log(level, data)
method on descendants.
Autogenerated Trace ID is atached to each log. If you need control over traceId generation, implement getTraceId(reqOptions, settings)
method.
Testing
Depending on selected approach use setMock(mockFuction)
or implement _axios(axiosOptions)
method. Both mockFuction
and _axios
will receive axios options instead of axios instance, and should return expected result. Default mock function is () => ({ data: 1 })
.
To check examples of api mocks and tesing, see implementation section.
Implementations
Looking for more examples? Check real implementations of famous APIs:
| API | Organization | Reference | Examples | |----|---|----------|-----| | Telegram Bot | Telegram | Bot API | sns-telegram-bot semantic-release-telegram | Telegra.ph | Telegram | Telegraph API | semantic-release-telegram | AWS SNS | Amazon | AWS docs | sns-telegram-bot | Gitea | | Gitea Swagger | lalaps | GitHub Apps | Microsoft | Apps Reference | lalaps | GitHub Repos | Microsoft | Repositories Reference | lalaps | Heroku | Salesforce | Platform API Reference | semantic-release-heroku | JIRA | Atlassian | REST API | atlassian | Confluence | Atlassian | REST API | atlassian
Contribute
Make the changes to the code and tests. Then commit to your branch. Be sure to follow the commit message conventions. Read Contributing Guidelines for details.