npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

base-api-client

v1.5.10

Published

Base API client backed by axios

Downloads

1,917

Readme

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:

| 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.