@tectonique/api-standards
v1.0.0
Published
TypeScript utilities for creating end to end type safe APIs with RFC 7807 (Problem Details) based error handling.
Downloads
795
Maintainers
Readme
🌩 API Standards
This library provides utilities for creating end to end type safe APIs.
The library advocates:
- API response envelopes
- Error handling with RFC 7807 Problem Details 🔗
📖 Table of contents
- 🌩 API Standards
- 📖 Table of contents
- 📦 NPM Package
- 💾 Installation
- 🏁 Goal
- 📑 Documentation
- 📜 Changelog
- 🦔 Author
📦 NPM Package
💾 Installation
Using npm:
npm i @tectonique/api-standards
Using yarn:
yarn add @tectonique/api-standards
🏁 Goal
The goal of the library is to help you create type safe code like this:
import { ResponseEnvelopes } from "@tectonique/api-standards"
// Import response and error (problem detail) types
import { ProblemDetailSuperType } from "@backend/ProblemDetailSuperType"
import { API_GetUsers_Response } from "@backend/ApiResponses"
// Make the API call
const data = await axios.get("/api/users")
.then((response) => response.data)
.catch((error) => error.response.data)
// Check and inspect envelope
if ( ResponseEnvelopes.isEnvelope(data) ) {
const envelope = data as ResponseEnvelopes.Envelope<
ProblemDetailSuperType,
API_GetUsers_Response
>
// Success envelope ... obviously ^^
if ( envelope.success ) {
console.log(
"User email adresses:",
envelope.payload.map(user => user.email).join(', ')
)
// Problem detail
} else if ( envelope.type === "unauthorized" ) {
throw new Error("Session expired")
} else {
throw new Error("Unhandled problem detail: " + envelope.type)
}
} else {
throw new Error("Didn't receive an envelope")
}