1.5.10 β€’ Published 1 year ago

base-api-client v1.5.10

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Logo

base-api-client

Base API client backed by axios.

Version Bundle size Downloads

CodeFactor SonarCloud Codacy Scrutinizer

Dependencies Security Build Status Coverage Status

Commit activity FOSSA License Made in Ukraine

πŸ‡ΊπŸ‡¦ 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

Platform Status

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

  1. url - base URL of the API. Can consist apiPrefix. Will be cast to nodeJS URL object.
  2. 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:

APIOrganizationReferenceExamples
Telegram BotTelegramBot API sns-telegram-bot semantic-release-telegram
Telegra.phTelegramTelegraph APIsemantic-release-telegram
AWS SNSAmazonAWS docssns-telegram-bot
GiteaGitea Swaggerlalaps
GitHub AppsMicrosoftApps Referencelalaps
GitHub ReposMicrosoftRepositories Referencelalaps
HerokuSalesforcePlatform API Referencesemantic-release-heroku
JIRAAtlassianREST APIatlassian
ConfluenceAtlassianREST APIatlassian

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.

1.5.10

1 year ago

1.5.9

2 years ago

1.5.5

2 years ago

1.5.4

2 years ago

1.5.8

2 years ago

1.5.7

2 years ago

1.5.6

2 years ago

1.5.3

3 years ago

1.5.2

3 years ago

1.5.1

3 years ago

1.5.0

3 years ago

1.4.5

3 years ago

1.4.4

3 years ago

1.4.3

3 years ago

1.4.2

3 years ago

1.4.1

3 years ago

1.4.0

3 years ago

1.3.0

3 years ago

1.2.2

3 years ago

1.2.1

3 years ago

1.2.0

3 years ago

1.1.0

3 years ago