1.0.25 • Published 8 months ago

typebox-client v1.0.25

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

typebox-client is a simple client for Typebox schema based api using:

  • Fully written in TypeScript
  • Typebox for easy json-schema writting
  • axios (more http client supported soon) as a http client

Table of Contents:


Installation

To get started, install typebox-client using npm or yarn:

npm install typebox-client
# or
yarn add typebox-client

Usage

Route definitions and api calls

import { loadRouteDefinitions, createRouteDefinition, Type } from 'typebox-client';

const definitions = {
  getUser: createRouteDefinition({
    method: 'GET',
    // Id parameter is dynamicaly injected in the final url.
    url: `/user/:id`,
    schema: {
      params: Type.Object({
        id: Type.String(),
      }),
      response: {
        200: Type.Array(
          Type.Object({
            name: Type.String(),
            age: Type.Number(),
          })
        ),
      },
    },
  }),
};

const [createClient, schemas] = loadRouteDefinitions(definitions);

// fastify
server.get('/user', { schema: schemas.getUser }, async (request, response) => {
  response.status(200).send([{ name: 'John', age: 30 }]);
});

// client
const apiClient = createClient(axios.create({ baseURL: 'localhost' }));

async () => {
  const user = await apiClient.getUser({ params: { id: 'my-user-id' } }).call();
  // { name: 'John', age: 30 }
};

Inject URL params

typebox-client use the /my-url/:my-param syntax to inject given parameters in the final url.

Access the final URL

Sometime, instead of calling the client method you will want to get the computed url. It's usefull to use it as a link href for instance.

const url = await apiClient.getUser({ params: { id: 'my-user-id' } }).url;
// https://localhost/user/my-user-id

That's it! You can now use typebox-client to create fully typed and safe api client.

1.0.25

8 months ago

1.0.24

8 months ago

1.0.23

8 months ago

1.0.22

8 months ago

1.0.21

10 months ago

1.0.20

10 months ago

1.0.19

10 months ago

1.0.18

10 months ago

1.0.17

10 months ago

1.0.16

10 months ago

1.0.15

10 months ago

1.0.14

11 months ago

1.0.13

11 months ago

1.0.12

11 months ago

1.0.11

11 months ago

1.0.10

11 months ago

1.0.9

11 months ago

1.0.8

11 months ago