Licence
MIT
Version
0.0.10
Deps
1
Size
27 kB
Vulns
0
Weekly
0
Create type safe client API instances based on
tectonique/api-standards .
API Standards – Client
This library is based on tectonique/api-standards .
It provides client utilities to make API requests and error handling 100% type safe.
Currently, type wrappers are provided for:
Table of contents
- API Standards – Client
- Table of contents
- NPM Package
- Installation
- Goal
- Documentation
- Changelog
- Author
NPM Package
Installation
Using npm:
npm i @tectonique/api-standards-client
Using yarn:
yarn add @tectonique/api-standards-client
Goal
When you have
- a type safe backend setup using tectonique/api-standards or tectonique/api-standards ,
- an exposed
ProblemDetailsSuperType - and this library installed you can create e.g. fully typed axios instances with error/Problem Detail handling!
You want to perform such 100% type safe API calls:
const createUserEnvelope = await MyApi.createUser(
"theo@testing.com",
"Theo Tester"
).catch(createProblemDetailHandler(pd => {
if (createUserEnvelope.type === "response-not-an-envelope") {
alert("Response is not an envelope!");
}
}));
console.log("User id: ", createUserEnvelope.payload.id);
Documentation
Axios with type safety
- Import your backend request/query/response types.
- Import your backend Problem Detail Super Type.
- Create a typable axios instance with
makeAxiosTypeSafe(axiosInstance). - Create your custom API instance with methods that use
get|post|put|patch|deleteof the typeable axios instance.
An example: Here is an example:
import axios from "axios";
import { ProblemDetailSuperType } from "@backend/ProblemDetailSuperType"
import { createTypeSafeAxios, ClientProblemDetailSuperType } from "@tectonique/api-standards-client";
type Create_User_Body = {
email: string;
name: string;
};
type Create_User_Response = {
id: string;
};
const {
verbs,
createProblemDetailHandler,
handleProblemDetail
} = createTypeSafeAxios<ProblemDetailSuperType | ClientProblemDetailSuperType>(axios);
const MyApi = {
createUser: (email: string, name: string) =>
verbs.post<Create_User_Response, Create_User_Body, undefined>(
"/users",
{ email, name }
),
};
const createUserEnvelope = await MyApi.createUser(
"theo@testing.com",
"Theo Tester"
).catch(createProblemDetailHandler(pd => {
if (createUserEnvelope.type === "response-not-an-envelope") {
alert("Response is not an envelope!");
}
}));
console.log("User id: ", createUserEnvelope.payload.id);
// OR wit try catch + await
try {
const createUserEnvelope = await MyApi.createUser(
"theo@testing.com",
"Theo Tester"
)
console.log("User id: ", createUserEnvelope.payload.id);
} catch ( error ) {
// await is important to catch rethrown non problem detail errors!
await handleProblemDetail(error, (pd) => {
if (createUserEnvelope.type === "response-not-an-envelope") {
alert("Response is not an envelope!");
}
})
}
Changelog
Author
Peter Kuhmann
GitHub: hedgehogs-mind
Tectonique