0.1.3 • Published 9 months ago

clientele v0.1.3

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

Clientele

Axios-based framework to build HTTP REST API clients for Node.js and the browser.

Installation

npm install clientele

Usage

Modules

Modules contain the definition and implementation of individual resources of an API.

modules/products.ts

import { ApiModule } from 'clientele';

// resource definition
export interface ProductsResource {
  list(): Promise<Product[]>;
  get(id: string): Promise<Product>;
  create(product: CreateProduct): Promise<Product>;
  update(id: string, product: UpdateProduct): Promise<Product>;
  delete(id: string): Promise<DeletedProduct>;
}

// module
const productsModule = ApiModule<ProductsResource> = {
  path: 'products',
  components: ({ makeRequest }) => ({
    list: () => makeRequest({
      method: 'GET',
    }),
    get: (id: string) => makeRequest({
      method: 'GET',
      path: id,
    }),
    create: (product: CreateProduct) => makeRequest({
      method: 'POST',
      data: product,
    }),
    update: (id: string, product: UpdateProduct) => makeRequest({
      method: 'PUT',
      path: id,
      data: product,
    }),
    delete: (id: string) => makeRequest({
      method: 'DELETE',
      path: id,
    }),
  }),
};

export default productsModule;

The modules contant defines the object paths for the resources.

modules\index.ts

import products from './products';

const modules = {
  products,
};

export default modules;

Client

The client extends the Clientele mixin with the provided modules and will specify other baseline configuration.

import Clientele from 'clientele';
import modules from './modules';

export interface ClientOptions {
  token: string;
}

export class Client extends Clientele(modules) {
  constructor({ token }: ClientOptions) {
    super({
      baseURL: 'https://api.service.com/v1',
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
  }
}

The new Client object and resources are typesafe and can be used with little effort by the developer.

const client = new Client({ token: API_TOKEN });

const products = await client.products.list();
const product = products[0];

await client.products.delete(product.id);

License

MIT

0.1.3

9 months ago

0.1.2

10 months ago

0.1.0

10 months ago

0.0.1

2 years ago