JavaScript
JavaScript のランタイムは、npm のパッケージ @comatype/javascript(packages/javascript)です。@comatype/typescript と同じランタイム(クライアント c、サーバ s、検証、ラッパー、cookie、キャッシュ)を、同じソースからビルドして、ただの ES モジュールと .d.ts の型宣言で配っています。Node.js 20 以上が必要です(Bun・Deno・Cloudflare Workers でも動きます)。
プロジェクトが JavaScript のときに使います。TypeScript なら、@comatype/typescript と --lang ts を使ってください。
生成されるもの#
"lang": "js" で comatype generate を実行すると、.comat ファイルごとに、値(スキーマ・ステータス・エンドポイント)の .js と、型の .d.ts が出ます。
<out>/ 既定は comatype
├─ types.js, types.d.ts 名前付きの型
├─ init.js, init.d.ts ラッパーのステータスと Wrappers 型
└─ user/put__id.js, put__id.d.ts エンドポイントごとに 1 組(パスは .comat の場所。[id] は __id になる)get.js
// Code generated by comatype generate. DO NOT EDIT.
import { t, defineStatus, defineEndpoint } from '@comatype/javascript'
import { Todo } from '../../types.js'
export const Params = t.object({
id: t.uuidv4(),
})
export const s200 = defineStatus(200, t.lazy(() => Todo), null)
export const s404 = defineStatus(404, t.object({
message: t.string(),
}), null)
export const endpoint = defineEndpoint({
method: "get",
path: "/todo/:id",
module: "todo/__id/get",
baseUrl: "http://localhost:3000",
wraps: [],
cookie: false,
params: Params,
search: null,
body: null,
requestHeaders: null,
responses: [s200, s404],
})
/** Same value as `endpoint` (callers import it as `path`) */
export const path = endpoint
const _ep = { path, endpoint, s200, s404 }
export default _ep相対 import には .js の拡張子が要ります(./comatype/user/put__id.js)。エディタに型を効かせるのは .d.ts です。jsconfig.json で checkJs を有効にすると、型の検査も受けられます。
クライアント#
api.js
// Functions that call each endpoint. Pass the generated path and statuses (s200 etc.) to c.xxx
// c.put(path, request, success status, ...error statuses)
// The result is the statuses passed (check `status`). 2xx is data, everything else is error
import { c } from '@comatype/javascript'
import { path, s200, s404 } from './comatype/user/put__id.js'
/** PUT /user/:id. The request has params and body, typed from put__id.comat (see put__id.d.ts) */
export async function putUser(id, user) {
const res = await c.put(path, { params: { id }, body: user }, s200, s404)
if (res.status === 200) return res.data // UserData (res.headers has X-Resource-Version)
return res.error // ApiError
}c.put(path, request, s200, s404)は、渡したステータスのどれかを返します。res.statusを調べてください。2xx はdata、それ以外はerrorです。- 渡していないステータスは
UnexpectedStatusError、不正な入力は、送る前にValidationErrorになります。JavaScript では、この検証が実行時の守りです。 - リクエストの渡し方、ほかのメソッド(
c.get、c.post、c.delete...)、リクエストヘッダ、cookie、キャッシュは、TypeScript のクライアントと同じです。
init.js
// Client init file: import and pass the implemented wrapper
// 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/javascript'
import { auth } from './wrappers/auth.js'
export function initComatype(baseUrl) {
// Node keeps no cookies, so take Set-Cookie into the jar and send it back with the next `cookie on` request
const jar = createCookieJar()
c.init({ baseUrl, wrappers: { auth }, cookie: { jar } })
return { jar }
}wrappers/auth.js
// Implement a wrapper as a function (req, next) and export it (corresponds to the `wrapper auth` of init.comat)
/** @type {import('@comatype/javascript').ComatypeWrap} */
export const auth = async (req, next) => {
// headerReq / header (X-Client-Version / X-Request-Id) of defaults.comat
req.headers['x-client-version'] = '1.0.0'
req.headers['x-request-id'] ??= crypto.randomUUID()
return next(req)
}サーバ#
user_put_id.js
import { s } from '@comatype/javascript'
import { path, s200, s404 } from './comatype/user/put__id.js'
import { db } from './db.js' // the app's own storage
s.put(path, (req) => {
// req.params.id: string, req.body: UserData
const version = db.update(req.params.id, req.body)
if (version === undefined) {
return s404({ error: { code: 'not_found', message: 'user not found' } })
}
// headerRes (X-Resource-Version) of user/defaults.comat
return s200({ data: db.find(req.params.id), headers: { 'X-Resource-Version': `v${version}` } })
})sにハンドラを登録して(s.put(path, req => ...))、@comatype/javascript/nodeのserve({ port, server: s })で起動します。Fetch API がある環境なら、s.handle(request)も使えます。TypeScript のサーバを参照してください。.comatに合わない入力は、ハンドラの前に 400 で返ります。
init.js
// Server init file: import and pass the implemented wrapper
// The cookie settings (name, httpOnly, etc.) are in init.comat
import { s } from '@comatype/javascript'
import { auth } from './wrappers/auth.js'
s.init({ wrappers: { auth } })wrappers/auth.js
// Implement a wrapper as a function (req, next) and export it (corresponds to the `wrapper auth` of init.comat)
// Generated from init.comat: the statuses a wrapper can return (s401)
import { s401 } from '../comatype/init.js'
import { db } from '../db.js' // the app's own storage
export const auth = async (req, next) => {
// A session cookie (browsers) or Authorization: Bearer (other clients)
const bearer = req.headers.authorization?.replace(/^Bearer /i, '')
const user = db.bySession(req.cookies.session ?? bearer)
if (!user) {
return s401({ error: { code: 'unauthorized', message: 'login required' } })
}
// On endpoints with `wrap auth` on, a handler can read req.ctx.user
return next({ ...req, ctx: { ...req.ctx, user } })
}注意#
@comatype/javascriptと@comatype/typescriptは別のパッケージです。1 つのプロジェクトで混ぜないでください(それぞれが別のc・s・状態を持ちます)。- 生成された
.jsは@comatype/javascriptを import するので、それを置くプロジェクトに入れてください。