0.4.0 • Published 3 years ago

@superdispatch/http v0.4.0

Weekly downloads
13
License
MIT
Repository
github
Last release
3 years ago

@superdispatch/http

npm npm minzipped size

Installation

yarn add @superdispatch/http

Usage

import { createHTTP } from '@superdispatch/http';

export function createAPI(token: string | undefined) {
  return createHTTP({
    baseURL: 'https://example.com',
    headers: !token ? undefined : { authorization: `Token ${token}` },
  });
}

export interface User {
  id: number;
  username: string;
  fullName: string;
  createdAt: number;
  updatedAt: number;
}

export function createUserAPI(token: string | undefined) {
  const { request, requestJSON } = createAPI(token);

  return {
    listUsers(
      status: 'active' | 'inactive' | 'deleted' = 'active',
      params?: { q?: string; page?: number; page_size?: number },
    ) {
      // This will make `listUsers` return `Promise<{ items: User[]; count: number }>`
      return requestJSON<{ items: User[]; count: number }>(
        // `{ status: 'active' }` -> `/users/active`
        // `{ status: 'inactive', q: 'foo' }` -> `/users/inactive?q=foo`
        ['/users/{status}{?params*}', { status, params }],
      );
    },

    getUser(id: number) {
      return requestJSON<
        User,
        // It is possible to strongly type allowed URI Template params.
        { id: number }
      >(['/users/{id}', { id }]);
    },

    addUser(values: Pick<User, 'username' | 'fullName'>) {
      // You can pass a HTTP method in the beggining of the URI template.
      return requestJSON<User>('POST /users', {
        // Passing `json` will transform it's value with `JSON.stringify` and
        // and set `content-type: application/json` header.
        json: values,
      });
    },

    editUser(id: number, values: Pick<User, 'username' | 'fullName'>) {
      return requestJSON<User, { id: number }>(['PUT /users/{id}', { id }], {
        json: values,
      });
    },

    deleteUser(id: number): Promise<Response> {
      // When we do not care about response body we can use `request` method
      // directly.
      return request<{ id: number }>(['DELETE /users/{id}', { id }]);
    },
  };
}
0.4.0

3 years ago

0.3.1

3 years ago

0.3.0

3 years ago

0.2.0

3 years ago

0.1.4

3 years ago

0.1.2

3 years ago

0.1.1

4 years ago

0.1.0

4 years ago

0.0.13

4 years ago

0.0.12

4 years ago

0.0.11

4 years ago

0.0.10

4 years ago

0.0.9

4 years ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.6

4 years ago

0.0.5

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago

0.0.2

4 years ago

0.0.1

4 years ago