TypeScript — server s
s from @comatype/typescript is a small router where you register handlers. The entry point is the Fetch API Request → Response, so it works on Node, Bun, Deno and Cloudflare Workers.
TypeScript
import { s } from '@comatype/typescript'
import { serve } from '@comatype/typescript/node'
import { path, s200, s404 } from '@/comatype/user/put__id'
s.put(path, (req) => {
// req.params.id: string, req.body: UserData (already validated)
const user = db.update(req.params.id, req.body)
if (!user) return s404({ error: { code: 'not_found', message: 'not found' } })
return s200({ data: user })
})
await serve({ port: 3000, server: s })Handlers#
Register them as in s.get(path, handler). A handler may be async.
req#
| Field | Meaning |
|---|---|
req.params | Path parameters (validated and converted) |
req.search | The query. {} if there is none |
req.body | The body. undefined for an endpoint with no body |
req.headers | Request headers (converted) |
req.cookies | The cookies that arrived |
req.ctx | Values added by the enabled wrappers (typed) |
Return value#
The endpoint's Response (built with s200({ ... }) and the like). A status that is not in the .comat, or a value of the wrong type, is a compile error.
TypeScript
return s200({ data: user }) // a 2xx has data
return s404({ error: { code: 'not_found', message: 'not found' } }) // anything else has error
return s204() // the body is none
return s200({ headers: { Allow: ['GET', 'POST'] } }) // response headers
return s200({ data: { uid }, cookie: { session: token } }) // Set-CookieEntry points#
| Way | When to use it |
|---|---|
serve({ port, server: s }) (@comatype/typescript/node) | Start it as a Node http server |
nodeListener(s) | Pass it to an existing http.createServer |
s.handle(request) | Make a Response from a Fetch API Request. Bun / Deno / Workers, and tests |
Behavior#
- Validation: if the input is invalid, it returns
400({ code: 'validation_error', message, path }) without calling the handler. If the body is not JSON,400(invalid_json). - Output validation: the handler's return value is validated too. A status that is not in the
.comat, or a body of the wrong type, gives500({ code: 'internal_error' }) and the details are not shown to the client. Exceptions are handled the same way. - Routing: static segments win over dynamic ones, a trailing
/is ignored, a path that matches with the wrong method gives405(withAllow), and no match gives404. Registering the same method and the same path shape twice is an error at registration. - Initializing:
s.init({ wrappers, onError }).onErrorreceives exceptions from handlers and wrappers, and the cause of responses that do not match the.comat.
Real example#
TypeScript
import { s } from '@comatype/typescript'
import { path, s200, s404 } from '@/comatype/user/put__id'
import { db } from './db'
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}` } })
})TypeScript
// user/(noauth)/post_login.comat -> POST /user/login. The group (noauth) is not part of the path
import { s } from '@comatype/typescript'
import { path, s200, s401 } from '@/comatype/user/post_login'
import { db } from './db'
// wrap auth is off, so it is called even when not logged in
s.post(path, (req) => {
const token = db.login(req.body.email, req.body.password)
if (!token) {
return s401({ error: { code: 'invalid_credentials', message: 'email or password is wrong' } })
}
const user = db.bySession(token)!
// cookie: the key is the name of `cookie session { ... }` in init.comat. httpOnly / secure / sameSite follow the settings in init.comat
// string -> Set-Cookie with that value / { value, maxAge, expires, path, domain } -> changes only this issue / null -> delete
return s200({ data: { uid: user.uid }, cookie: { session: { value: token, maxAge: 3600 } } })
})TypeScript
// Implement a wrapper as a value of type ComatypeWrap and export it (corresponds to the `wrapper auth` of init.comat)
import type { ComatypeWrap } from '@comatype/typescript'
// Generated from init.comat: the ctx type (AuthCtx) and the statuses a wrapper can return (s401)
import { s401, type AuthCtx } from '@/comatype/init'
import { db } from '../db'
// ComatypeWrap<AuthCtx>: the type of values that can be added to ctx. On endpoints with `wrap auth` on, a handler can read req.ctx.user, typed
export const auth: ComatypeWrap<AuthCtx> = 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' } })
}
return next({ ...req, ctx: { ...req.ctx, user } })
}TypeScript
// Start the server: PORT=3000 pnpm start (a free port if PORT is not set)
import { serve } from '@comatype/typescript/node'
import { s } from './app'
const server = await serve({ port: Number(process.env.PORT ?? 0), server: s })
const address = server.address()
const port = typeof address === 'object' && address ? address.port : 0
// The test reads this port
console.log(`LISTENING http://127.0.0.1:${port}`)