1.1.1 • Published 5 months ago

@typed-web-api/client v1.1.1

Weekly downloads
-
License
ISC
Repository
github
Last release
5 months ago

@typed-web-api/client

Client library to infer the return type of fetch requests based on a web API's type declaration generated via @typed-web-api/common.

Example

Given the following sample fetch call:

/* ... */

const response = await fetch(`/users`, { method: 'get' });
const users = await response.json(); // Inferred type => any

This is how to get typed response payloads by using typedFetch (given a WebApiTypes types declaration):

import { getTypedFetch } from '@typed-web-api/client';
import { WebApiTypes } from '...';

const typedFetch = getTypedFetch<WebApiTypes>();

/* ... */

const response = await typedFetch('/users_get');
const users = await response.json(); // Inferred type => User[]

API

getTypedFetch\<TApi>(options)

Returns

An instance of typedFetch, configured for the TApi type.

Arguments

  • TApi: Web API's type declaration.
  • options:

    nametypedefaultdescription
    baseUrlstring?undefinedA string that will be prepended to the URL of all fetch requests
    fetchWindow'fetch'?this.fetchA function that issues Http requests

Examples

const typedFetch = getTypedFetch<MyApiType>();
const typedFetch = getTypedFetch<MyApiType>({ baseUrl: '/api' });
const typedFetch = getTypedFetch<MyApiType>({ fetch: nodeFetch });

typedFetch(endpointName, options)

Returns

A promise of an Http response, with a .json() method typed according to the TApi provided in the parent function (i.e. getTypedFetch).

Arguments

  • endpointName: The target web API endpoint name (e.g. /users_get).
  • options:

    nametypedefaultdescription
    initRequestInit?undefinedRequestInit properties that will be passed to the fetch call (except for the method and conditional overrides depending on the provided options).
    urlPrefixstring?undefinedA string that will be prepended to the endpoint URL.

    For endpoints with typed request payload (i.e. endpoint definitions that use JsonBody, QueryString and/or UrlParams), additional parameters are available:

    nametypedefaultdescription
    jsonBodyextends anyundefinedObject that will be stringified and sent as the request body. When provided, the Content-Type header will be will set/overwritten with application/json.
    queryStringextends { [key: string]: string }?undefinedKey-value dictionary with query string parameters to be added to the URL.
    urlParamsextends { [key: string]: string }?undefinedKey-value dictionary with parameters to be replaced in the URL.

Examples

const users = await typedFetch('/users_get');
const usersPage = await typedFetch('/users_get', { queryString: { limit: '30', skip: '30' } });

const loginResponse = await typedFetch('/login_post', { jsonBody: { email: '', password: '' } });

const user = await typedFetch('/users/:userId_get', { urlParams: { userId: 'xyz' } });
1.1.1

5 months ago

1.1.0

5 months ago

1.0.0

6 months ago