1.1.2 • Published 1 year ago
@typed-web-api/client v1.1.2
@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 => anyThis is how to get typed response payloads by using typedFetch (given the sample WebApiEndpoints type described in @typed-web-api/common):
import { getTypedFetch } from '@typed-web-api/client';
import { WebApiEndpoints } from '...';
const typedFetch = getTypedFetch<WebApiEndpoints>();
/* ... */
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:
name type default description baseUrl string? undefinedA string that will be prepended to the URL of all fetch requests fetch Window'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:
name type default description init RequestInit? undefinedRequestInit properties that will be passed to the fetch call (except for the methodand conditional overrides depending on the provided options).urlPrefix string? undefinedA string that will be prepended to the endpoint URL. For endpoints with typed request payload (i.e. endpoint definitions that use
JsonBody,QueryStringand/orUrlParams), additional parameters are available:name type default description jsonBody extends anyundefinedObject that will be stringified and sent as the request body. When provided, the Content-Typeheader will be will set/overwritten withapplication/json.queryString extends { [key: string]: string }?undefinedKey-value dictionary with query string parameters to be added to the URL. urlParams extends { [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('/users/login_post', {
jsonBody: { email: '...', password: '...' },
});
const user = await typedFetch('/users/:userId_get', { urlParams: { userId: 'xyz' } });