@api-ts/superagent-wrapper
Combines an api spec with superagent
/supertest
to create a type-checked api client.
Getting started
First, either define or import an io-ts-http
api spec. The following one will be used
for this guide:
import * as h from '@api-ts/io-ts-http';
import * as t from 'io-ts';
import { NumberFromString } from 'io-ts-types';
export const Example = t.type({
foo: t.string,
bar: t.number,
});
export const GenericAPIError = t.type({
message: t.string,
});
export const PutExample = h.httpRoute({
path: '/example/{id}',
method: 'PUT',
request: h.httpRequest({
params: {
id: NumberFromString,
},
body: {
example: Example,
},
}),
response: {
ok: Example,
invalidRequest: GenericAPIError,
},
});
export const ExampleAPI = h.apiSpec({
'api.example': {
put: PutExample,
},
});
ExampleAPI
can then be used to create a type-safe api client for either superagent
or supertest
. This requires two steps: wrapping the superagent
/supertest
instance,
then binding it to the api spec.
For superagent
:
import { superagentRequestFactory, buildApiClient } from '@api-ts/superagent-wrapper';
import superagent from 'superagent';
import { ExampleAPI } from './see-the-above-example';
const BASE_URL = 'http://example.com/';
const requestFactory = superagentRequestFactory(superagent, BASE_URL);
export const apiClient = buildApiClient(requestFactory, ExampleAPI);
For supertest
the process is almost identical except that supertest
itself handles
knowing the root api url:
import { supertestRequestFactory, buildApiClient } from '@api-ts/superagent-wrapper';
import supertest from 'superagent';
import { ExampleAPI } from './see-the-above-example';
import { app } from '../src/index';
const request = supertest(app);
const requestFactory = superatestRequestFactory(request);
export const apiClient = buildApiClient(requestFactory, ExampleAPI);
The resulting apiClient
can then be imported elsewhere and used:
import { apiClient } from './api-client-example';
const doSomething = async () => {
const response = await apiClient['api.example']
.put({ id: 42, example: { foo: 'hello', bar: 1 } })
.decode();
if (response.status === 200) {
const { foo, bar } = response.body;
} else if (response.status === 400) {
console.log(response.body.message);
} else {
if (
response.body &&
typeof response.body === 'object' &&
response.body.hasOwnProperty('message')
) {
console.log(response.body.message);
}
}
};
For convenience, a decodeExpecting
function is also added to requests. It accepts an
HTTP status code and throws if either the response code doesn't match, or it does but
the response body failed to decode.
const expectOk = async () => {
const response = await apiClient['api.example']
.put({ id: 42, example: { foo: 'hello', bar: 1 } })
.decodeExpecting(200);
const { foo, bar } = response.body;
};