TypeScript — client c
c from @comatype/typescript takes a generated path (the endpoint descriptor) and statuses, and builds a typed fetch.
import { c } from '@comatype/typescript'
import { path, s200, s404 } from '@/comatype/user/put__id'
const res = await c.put(path, { params: { id }, body: user }, s200, s404)
if (res.status === 200) res.data // UserData
if (res.status === 404) res.error // ApiErrorCalling#
c.get(path, ...) c.post(path, ...) c.put(path, ...) c.patch(path, ...)
c.delete(path, ...) c.options(path, ...) c.query(path, ...) c.head(path, ...)delete is a reserved word, so write c.delete() rather than a named import. Passing a PUT endpoint to c.get() is a compile error.
How to pass the request#
The shape of the endpoint decides the arguments.
| Endpoint | Call |
|---|---|
No params / search / body | c.get(path, s200) |
body only | c.post(path, body, s200) (pass the body as it is) |
search only, all optional | Either c.get(path, s200) or c.get(path, { search: { limit } }, s200) |
| Anything else | An object { params, search, body } |
Request headers (header / headerReq) are not passed as arguments. Add them with c.init({ headers }) or c.with({ headers }).
Default import#
Every generated module also has a default export that bundles path, endpoint, the statuses (s200 ...) and the types (Request, Response, Body ...). You can import the endpoint as one name instead of renaming each export with as.
import user_put__id from '@/comatype/user/put__id'
const res = await c.put(user_put__id.path, { params: { id }, body: user }, user_put__id.s200, user_put__id.s404)
const body: user_put__id.Body = userReturn value#
A union of the responses for the statuses you passed (s200, s404 ...). You can narrow it with status.
const { status, data, error } = await c.post(path, input, s200) // destructuring works too- A 2xx has
data, anything else haserror. A status whose body isnonehas neither. - Response headers are in
res.headers(fors200 none, { Allow: string[] },res.headers.Allow). - If a status you did not pass comes back, it throws
UnexpectedStatusError(you do not have to passs500every time).
Initializing#
import { c, createCookieJar } from '@comatype/typescript'
import { auth } from './wrappers/auth'
c.init({
baseUrl: 'https://api.example.com',
wrappers: { auth }, // a type error unless every wrapper in init.comat is there
cookie: { jar: createCookieJar() }, // for environments that keep no cookies, such as Node
headers: { 'x-app': 'web' }, // headers added to every request
})The priority of baseUrl is c.init({ baseUrl }) > the COMATYPE_BASE_URL environment variable > baseUrl in init.comat.
c.with()#
Returns another client with extra headers or an AbortSignal (the settings are shared with the original client).
await c.with({ headers: { 'x-trace': '1' }, signal }).get(path, s200)Validation#
- Before sending, it validates
params,search, headers andbody. If anything is invalid it throwsValidationErrorwithout any network call (pathis set in a form likebody.email). - After receiving, it
parses the body into the type, and converts headers from strings toint/bool/ arrays before validating.int64becomesbigint.
See also Validation and errors.
Real example#
// Functions that call each endpoint. Pass the generated path and statuses (s200 etc.) to c.xxx
// c.post(path, body, success status, ...error statuses)
// The result is the union of the statuses passed (narrow it with status). 2xx is data, everything else is error
// `delete` is a reserved word in TS, so call it as c.delete() instead of a named import
import { c } from '@comatype/typescript'
import get_user from '@/comatype/get_user'
import options_user from '@/comatype/options_user'
import post_user from '@/comatype/post_user'
import query_user from '@/comatype/query_user'
import user_delete__id from '@/comatype/user/delete__id'
import user_get from '@/comatype/user/get'
import user_get_me from '@/comatype/user/get_me'
import user_get_ping from '@/comatype/user/get_ping'
import user_post_login from '@/comatype/user/post_login'
import user_profile_get from '@/comatype/user/profile/get'
import user_put__id from '@/comatype/user/put__id'
/** Sign up (POST /user). The body is Body (no uid) */
export const postUser = (input: post_user.Body) => c.post(post_user.path, input, post_user.s200).then((res) => res.data)
/** GET /user/:id (a sample with an explicit path). It has params and search, so pass a Request */
export const getUser = (id: string, verbose?: boolean) =>
c.get(get_user.path, { params: { id }, search: { verbose } }, get_user.s200, get_user.s404)
// #region put-user
/** PUT /user/:id */
export const putUser = (id: string, user: user_put__id.Body) =>
c.put(user_put__id.path, { params: { id }, body: user }, user_put__id.s200, user_put__id.s404)
// #endregion put-user
/** DELETE /user/:id */
export const deleteUser = (id: string) => c.delete(user_delete__id.path, { params: { id } }, user_delete__id.s204, user_delete__id.s404)
/** GET /user?limit= */
export const listUsers = (limit?: number) => c.get(user_get.path, { search: { limit } }, user_get.s200)
/** QUERY /user: send the search criteria in the body */
export const queryUsers = (condition: query_user.Body) => c.query(query_user.path, condition, query_user.s200)
/** OPTIONS /user: there are no params / search / body, so no request argument is needed */
export const optionsUser = () => c.options(options_user.path, options_user.s200)
/** POST /user/login. On success the server issues a Set-Cookie */
export const login = (input: user_post_login.Body) => c.post(user_post_login.path, input, user_post_login.s200, user_post_login.s401)
/** GET /user/profile (wrap auth is on, so 401 without login) */
export const getProfile = () => c.get(user_profile_get.path, user_profile_get.s200, user_profile_get.s401)
/** GET /user/me (`path ./me`) */
export const getMe = () => c.get(user_get_me.path, user_get_me.s200, user_get_me.s401)
/** GET /ping (a fixed path. wrap auth off) */
export const ping = () => c.get(user_get_ping.path, user_get_ping.s200)
/** Logout: drop the cookie jar and the cache (responses with `cache`). The cache key does not include Authorization, so always call this when the user changes */
export const logout = () => c.clearCache()// Client init file: import and pass the implemented ComatypeWrap
// The base url defaults to baseUrl in init.comat. Override with the COMATYPE_BASE_URL environment variable or the baseUrl below
import { c, createCookieJar } from '@comatype/typescript'
import { auth } from './wrappers/auth'
export function initComatype(baseUrl?: string) {
// Node keeps no cookies, so take Set-Cookie into the jar and send it back with the next `cookie on` request
// (In browsers, use `cookie: { credentials: 'include' }` instead of the jar)
const jar = createCookieJar()
c.init({
baseUrl,
// With the generated types, a missing wrapper declared in init.comat, or a wrong type, is a compile error
wrappers: { auth },
cookie: { jar },
})
return { jar }
}