JavaScript

The JavaScript runtime is the npm package @comatype/javascript (packages/javascript). It is the same runtime as @comatype/typescript (the client c, the server s, validation, wrappers, cookies and caching), built from the same source and shipped as plain ES modules with .d.ts declarations. It needs Node.js 20 or later (it also works on Bun, Deno and Cloudflare Workers).

Use it when your project is JavaScript. If you use TypeScript, use @comatype/typescript and --lang ts.

What is generated#

comatype generate with "lang": "js" writes, for each .comat file, a .js file with the values (schemas, statuses, the endpoint) and a .d.ts file with the types:

<out>/                       default is comatype
├─ types.js, types.d.ts      Named types
├─ init.js, init.d.ts        Wrapper statuses and the Wrappers type
└─ user/put__id.js, put__id.d.ts   One pair per endpoint (the path is the location of the .comat file; [id] becomes __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

Relative imports need the .js extension (./comatype/user/put__id.js). The .d.ts files are what gives your editor the types: turn on checkJs in jsconfig.json to have them checked too.

Client#

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) returns the status you pass; check res.status. 2xx is data, everything else is error.
  • A status you did not pass throws UnexpectedStatusError, and invalid input throws ValidationError before any request is sent. In JavaScript this check is what protects you at run time.
  • The request, the other methods (c.get, c.post, c.delete, ...), request headers, cookies and caching work as in the TypeScript client.
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)
}

Server#

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}` } })
})
  • Register handlers on s (s.put(path, req => ...)) and start it with serve({ port, server: s }) from @comatype/javascript/node, or use s.handle(request) on any runtime that has the Fetch API. See the TypeScript server.
  • A request that does not match the .comat is answered with 400 before your handler runs.
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 } })
}

Notes#

  • @comatype/javascript and @comatype/typescript are separate packages. Do not mix them in one project (each has its own c, s and state).
  • The generated .js files import @comatype/javascript, so install it in the project that holds them.