Response classes for the Node.js HTTP server.
This library is framework agnostic, but here is an example on how to use it with Express and TypeScript:
index.ts
import express, { Request } from 'express'
import { Response } from '@response/types'
import * as users from './routes/users'
const app = express()
type Method = 'get' | 'post' | 'put' | 'delete'
type Handler = (req: Request) => Promise<Response>
function route (method: Method, path: string, handler: Handler): void {
app[method](path, (req, res, next) => handler(req).then(result => result.write(res)).catch(next))
}
route('get', '/v1/users', users.list)
route('post', '/v1/users', users.post)
route('get', '/v1/users/:id', users.get)
route('delete', '/v1/users/:id', users.delete)
routes/users.ts
import type { Request } from 'express'
import type { Response } from '@response/types'
import getJsonBody from '@body/json'
import empty from '@response/empty'
import json from '@response/json'
import redirect from '@response/redirect'
export async function list (req: Request): Promise<Response> {
const users = [/* ... */]
return json(users)
}
export async function post (req: Request): Promise<Response> {
const input = await getJsonBody(req)
const id = '/* ... */'
return redirect(`/v1/users/${id}`)
}
export async function get (req: Request): Promise<Response> {
const user = { /* ... */ }
return json(user)
}
export async function delete (req: Request): Promise<Response> {
/* ... */
return empty()
}