Skip to content

TypeScript client

A TypeScript client, @tourpingo/client, generated from the published contract with its errors typed, is coming with issue #486.

Every example in these guides has a TypeScript tab that uses fetch, which Node, Bun, Deno and Cloudflare Workers all have. To type the answers, you can generate types from the spec with any OpenAPI 3.1 tool:

Wrap fetch once, so every call sends the key and every error becomes one type you can switch on by code:

type Problem = { status: number; code: string; detail: string; [field: string]: unknown }
export class TourpingoError extends Error {
constructor(readonly problem: Problem) {
super(`${problem.code}: ${problem.detail}`)
}
}
export const tourpingo = async <T>(path: string, init: RequestInit = {}): Promise<T> => {
const res = await fetch(new URL(path, process.env.TP_API_URL), {
...init,
headers: { "Tp-Publishable-Key": process.env.TP_KEY ?? "", "Content-Type": "application/json", ...init.headers },
})
const body = res.status === 204 ? null : await res.json()
if (!res.ok) throw new TourpingoError(body as Problem)
return body as T
}