TypeScript — クライアント c

@comatype/typescript の c が、生成された path(エンドポイントの記述子)とステータスを受け取って、型の付いた fetch を作ります。

TypeScript
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  // ApiError

呼び出し#

TypeScript
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 は予約語なので、名前付き import ではなく c.delete() と書きます。c.get() に PUT のエンドポイントを渡すと、コンパイルエラーです。

リクエストの渡し方#

エンドポイントの形で、引数が決まります。

エンドポイント呼び出し
params / search / body が無いc.get(path, s200)
body だけc.post(path, ボディ, s200)(ボディをそのまま渡す)
search だけで、全部任意c.get(path, s200) でも c.get(path, { search: { limit } }, s200) でも
それ以外{ params, search, body } のオブジェクト

リクエストヘッダ(header / headerReq)は引数では渡さず、c.init({ headers }) か c.with({ headers }) で付けます。

デフォルトの import#

生成された各モジュールには、path・endpoint・ステータス(s200 ...)・型(Request Response Body ...)をまとめた default export もあります。as で 1 つずつ別名を付けなくても、エンドポイントを 1 つの名前で import できます。

TypeScript
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 = user

戻り値#

渡したステータス(s200、s404 ...)のレスポンスの和です。status で絞り込めます。

TypeScript
const { status, data, error } = await c.post(path, input, s200)   // 分割代入もできる
  • 2xx は data、それ以外は error です。ボディが none のステータスには、どちらもありません。
  • レスポンスヘッダは res.headers です(s200 none, { Allow: string[] } なら res.headers.Allow)。
  • 渡していないステータスが返ったときは、UnexpectedStatusError を投げます(s500 を毎回渡す必要はありません)。

初期化#

TypeScript
import { c, createCookieJar } from '@comatype/typescript'
import { auth } from './wrappers/auth'

c.init({
  baseUrl: 'https://api.example.com',
  wrappers: { auth },                 // init.comat の wrapper が揃っていないと、型エラー
  cookie: { jar: createCookieJar() }, // Node など、cookie を保持しない環境
  headers: { 'x-app': 'web' },        // 全リクエストに付けるヘッダ
})

baseUrl の優先順位は、c.init({ baseUrl }) > 環境変数 COMATYPE_BASE_URL > init.comat の baseUrl です。

c.with()#

ヘッダや AbortSignal を足した、別のクライアントを返します(設定は元のクライアントと共有)。

TypeScript
await c.with({ headers: { 'x-trace': '1' }, signal }).get(path, s200)

検証#

  • 送る前に params search ヘッダ body を検証します。不正なら通信せずに ValidationError(path が body.email のような形で入る)。
  • 受け取った後は、ボディを parse して型に直し、ヘッダは文字列から int / bool / 配列に直してから検証します。int64 は bigint になります。

バリデーションとエラーも見てください。

実例#

TypeScript
// 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()
TypeScript
// 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 }
}