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

modular-api-client

v1.0.9

Published

[![coverage](https://codecov.io/gh/Yohaido159/modular-api-client/branch/master/graph/badge.svg)](https://codecov.io/gh/Yohaido159/modular-api-client)

Downloads

17

Readme

Modular API Client

coverage

This package offers a customizable API client using decorators, enabling the modification of request headers, addition of authentication, versioning, and more.

Installation

To install the package, you can use the following npm command:

npm install modular-api-client --save

Usage

Here's an example of how you might use the package in your code:

Basic Usage

Importing the Client

import {
  ApiClient,
  AxiosBaseApiClient,
  AxiosVersionDecorator,
  AxiosHeadersDecorator,
  AxiosDataDecorator,
} from 'modular-api-client';

Creating an Instance

const client = new ApiClient(new AxiosBaseApiClient('https://api.example.com'));

Adding Decorators

client.addDecorator({ decorator: AxiosVersionDecorator, params: { version: 'v1' } });
client.addDecorator({ decorator: AxiosHeadersDecorator, params: { 'X-Custom-Header': 'Custom Value' } });
client.addDecorator({ decorator: AxiosDataDecorator });

Making Requests

client.get({ url: '/users/1' }).then((response) => {
  console.log(response);
});

Result

request url: https://api.example.com/v1/users/1
request headers: { 'X-Custom-Header': 'Custom Value' }
response: { userId: 1, name: 'John Doe' }

Available Decorators

Advanced Usage

Creating Custom Decorators

Custom decorators allow you to extend the core functionality of the API client and encapsulate specific behavior related to logging, timing, authentication, headers, etc. By following the structure provided, you can create decorators that can be easily added or removed.

Implementing a Basic Custom Decorator

this example will apply the decorator to the GET method

// retry.decorator.js
import { Decorator } from 'modular-api-client';

export class RetryDecorator extends Decorator {
  constructor(apiClient, params) {
    super(apiClient);
    this.retries = params.retries;
    this.delay = params.delay;
  }

  get(options) {
    const attempt = async ({ retriesLeft }) => {
      try {
        return await this.apiClient.get(options);
      } catch (error) {
        if (retriesLeft > 0) {
          return new Promise((resolve) =>
            setTimeout(() => resolve(attempt({ retriesLeft: retriesLeft - 1 })), this.delay),
          );
        }
        return Promise.reject(error);
      }
    };

    return attempt({ retriesLeft: this.retries });
  }
}

// index.js
import { ApiClient, AxiosBaseApiClient } from 'modular-api-client';

const client = new ApiClient(new AxiosBaseApiClient('https://api.example.com'));
client.addDecorator({ decorator: RetryDecorator, params: { retries: 3, delay: 1000 } });
client.get({ url: '/users/1' }).then((response) => {
  console.log(response);
});

Implementing a Custom Decorator for all methods

this example will apply the decorator to all methods

export class RetryDecorator extends Decorator {
    // ...
    all(method, options) {
        const attempt = async ({ retriesLeft }) => {
        try {
            return await this.apiClient[method](options);
            // ...
        }
        // ...
        });
    // ...
    }
}

Applying Decorators to Specific Scope

'with' Method

The with method allows you to apply decorators to a specific scope.

Example

const client = new ApiClient(new AxiosBaseApiClient('https://api.example.com'));
clien.get({ url: '/users/1' });
// -> https://api.example.com/users/1

client.with({ decorator: AxiosVersionDecorator, params: { version: 'v1' } }).get({ url: '/users/1' });
// -> https://api.example.com/v1/users/1

client.get({ url: '/users/1' });
// -> https://api.example.com/users/1

'without' Method

The without method allows you to remove decorators from a specific scope.

Example

const client = new ApiClient(new AxiosBaseApiClient('https://api.example.com'));
client.addDecorator({ decorator: AxiosVersionDecorator, params: { version: 'v1' } });

client.get({ url: '/users/1' });
// -> https://api.example.com/v1/users/1

client.without({ decorator: AxiosVersionDecorator }).get({ url: '/users/1' });
// -> https://api.example.com/users/1

client.get({ url: '/users/1' });
// -> https://api.example.com/v1/users/1

Available Decorators API

AxiosVersionDecorator

Adds a version to the request URL.

Parameters

| Name | Type | Description | | ------- | ------ | ------------------------------------------------------------------------ | | version | string | The version to add to the request URL. The version is added as a prefix. |

Example

client.addDecorator({ decorator: AxiosVersionDecorator, params: { version: 'v1' } });

JWTRefreshDecorator

If the JWT token is expired, refreshes it and retries the request.

Parameters

| Name | Type | Description | | --------------- | -------- | ------------------------------------------------------------------- | | refreshCallback | function | A function that returns a promise that resolves to a new JWT token. |

Example

client.addDecorator({ decorator: JWTRefreshDecorator, params: { refreshCallback: <your-refresh-callback> } });

AxiosHeadersDecorator

Adds custom headers to the request.

Parameters

| Name | Type | Description | | --------- | ------ | --------------------------------------------- | | | string | The name of the header to add to the request. |

Example

client.addDecorator({ decorator: AxiosHeadersDecorator, params: { 'X-Custom-Header': 'Custom Value' } });

AxiosDataDecorator

Receives only the data from the response.

Parameters

None

Example

client.addDecorator({ decorator: AxiosDataDecorator });

RetryDecorator

Retries the request if it fails.

Parameters

| Name | Type | Description | | ------- | ------ | -------------------------------------------------------------------------- | | retries | number | The number of times to retry the request if it fails. The default is 3. | | delay | number | The delay in milliseconds between each retry. The default is 1000 (1 sec). |

Example

client.addDecorator({ decorator: RetryDecorator, params: { retries: 3, delay: 1000 } });