|
| 1 | +import { ApiEndpointsOfVerb, ApiGetEndpoints, ApiPatchEndpoints, ApiPostEndpoints } from '@common/api-endpoints.js' |
| 2 | +import { ApiResponse } from '@common/api-response.js' |
| 3 | +import express, { NextFunction, Request, Response, Router } from 'express' |
| 4 | +import type { RouteParameters } from 'express-serve-static-core' |
| 5 | +import { configuration } from '../config/config.mjs' |
| 6 | + |
| 7 | +/** |
| 8 | + * Type for handlers for given method. |
| 9 | + */ |
| 10 | +export type HandlerOfVerb<V extends string, E extends keyof ApiEndpointsOfVerb<V>> = ( |
| 11 | + req: Request< |
| 12 | + // allows inferring ":parameters" |
| 13 | + RouteParameters<E>, |
| 14 | + // unknown, due to chaining |
| 15 | + unknown, |
| 16 | + // type of request body and query taken from ApiEndpointDefinitions |
| 17 | + ApiEndpointsOfVerb<V>[E]['request']['body'], |
| 18 | + ApiEndpointsOfVerb<V>[E]['request']['query'] |
| 19 | + >, |
| 20 | + res: Response<ApiEndpointsOfVerb<V>[E]['response']>, |
| 21 | + next: NextFunction, |
| 22 | +) => void | Promise<void> |
| 23 | + |
| 24 | +/** |
| 25 | + * Type for GET handlers. |
| 26 | + */ |
| 27 | +export type GetHandler<E extends keyof ApiGetEndpoints> = HandlerOfVerb<'GET', E> |
| 28 | + |
| 29 | +/** |
| 30 | + * Type for POST handlers. |
| 31 | + */ |
| 32 | +export type PostHandler<E extends keyof ApiPostEndpoints> = HandlerOfVerb<'POST', E> |
| 33 | + |
| 34 | +/** |
| 35 | + * Type for PATCH handlers. |
| 36 | + */ |
| 37 | +export type PatchHandler<E extends keyof ApiPatchEndpoints> = HandlerOfVerb<'PATCH', E> |
| 38 | + |
| 39 | +/** |
| 40 | + * Base class for controllers. |
| 41 | + * In your child class, attach handlers using `attach<Verb>` methods in the |
| 42 | + * constructor. |
| 43 | + */ |
| 44 | +export class Controller { |
| 45 | + /** Router object to pass in `express.use` */ |
| 46 | + router: Router |
| 47 | + |
| 48 | + constructor(public config: configuration) { |
| 49 | + this.router = express.Router() |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Send a well-typed JSON response with optional debug info. |
| 54 | + * @param res Express response. |
| 55 | + * @param body Response body. Type is derived from endpoint registry. |
| 56 | + * @param dbg Additional debug info. |
| 57 | + * @see {@link ApiResponse} |
| 58 | + */ |
| 59 | + respond<T>(res: Response<ApiResponse<T>>, body: T, dbg?: unknown) { |
| 60 | + res.json({ |
| 61 | + body: body, |
| 62 | + dbg, |
| 63 | + }) |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * Send a well-typed error with code 400 (Bad request), additional error text |
| 68 | + * and optional debug info. |
| 69 | + * @param res Express response. |
| 70 | + * @param error Error object. |
| 71 | + * @param dbg Additional debug info. |
| 72 | + * @see {@link ApiResponse} |
| 73 | + */ |
| 74 | + requestError<T>(res: Response<ApiResponse<T>>, error: ApiResponse<T>['error'], dbg?: unknown) { |
| 75 | + res.status(400) |
| 76 | + res.json({ |
| 77 | + error, |
| 78 | + dbg, |
| 79 | + }) |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * Send a well-typed error with code 401 (Unauthorized), additional |
| 84 | + * error text and optional debug info. |
| 85 | + * @param res Express response. |
| 86 | + * @param error Error object. |
| 87 | + * @param dbg Additional debug info. |
| 88 | + * @see {@link ApiResponse} |
| 89 | + */ |
| 90 | + unauthorizedError<T>(res: Response<ApiResponse<T>>, error: ApiResponse<T>['error'], dbg?: unknown) { |
| 91 | + res.status(401) |
| 92 | + res.json({ |
| 93 | + error, |
| 94 | + dbg, |
| 95 | + }) |
| 96 | + } |
| 97 | + |
| 98 | + /** |
| 99 | + * Send a well-typed error with code 500 (Internal server error), additional |
| 100 | + * error text and optional debug info. |
| 101 | + * @param res Express response. |
| 102 | + * @param error Error object. |
| 103 | + * @param dbg Additional debug info. |
| 104 | + * @see {@link ApiResponse} |
| 105 | + */ |
| 106 | + serverError<T>(res: Response<ApiResponse<T>>, error: ApiResponse<T>['error'], dbg?: unknown) { |
| 107 | + res.status(500) |
| 108 | + res.json({ |
| 109 | + error, |
| 110 | + dbg, |
| 111 | + }) |
| 112 | + } |
| 113 | + |
| 114 | + // Attach handler wrapper, serves two purposes: |
| 115 | + // 1. Provides a common try catch wrap around the handler. |
| 116 | + // 2. Allows type inferring from route (Express' types are too convoluted to |
| 117 | + // be overriden by declares IMHO). |
| 118 | + private attach<V extends 'get' | 'post' | 'patch', E extends keyof ApiEndpointsOfVerb<Uppercase<V>>>( |
| 119 | + verb: V, |
| 120 | + endpoint: E, |
| 121 | + handler: HandlerOfVerb<Uppercase<V>, E>, |
| 122 | + ) { |
| 123 | + this.router[verb](endpoint, async (req, res, next) => { |
| 124 | + try { |
| 125 | + await handler(req, res, next) |
| 126 | + // force a server error if the handler did not respond |
| 127 | + if (!res.writableEnded) { |
| 128 | + next('Handler did not respond') |
| 129 | + } |
| 130 | + } catch (error) { |
| 131 | + next(error) |
| 132 | + } |
| 133 | + }) |
| 134 | + } |
| 135 | + |
| 136 | + /** |
| 137 | + * Attach handler for GET endpoint. |
| 138 | + */ |
| 139 | + attachGet<E extends keyof ApiGetEndpoints>(endpoint: E, handler: GetHandler<E>) { |
| 140 | + this.attach('get', endpoint, handler) |
| 141 | + } |
| 142 | + |
| 143 | + /** |
| 144 | + * Attach handler for POST endpoint. |
| 145 | + */ |
| 146 | + attachPost<E extends keyof ApiPostEndpoints>(endpoint: E, handler: PostHandler<E>) { |
| 147 | + this.attach('post', endpoint, handler) |
| 148 | + } |
| 149 | + |
| 150 | + /** |
| 151 | + * Attach handler for PATCH endpoint. |
| 152 | + */ |
| 153 | + attachPatch<E extends keyof ApiPatchEndpoints>(endpoint: E, handler: PatchHandler<E>) { |
| 154 | + this.attach('patch', endpoint, handler) |
| 155 | + } |
| 156 | +} |
| 157 | + |
| 158 | +/** |
| 159 | + * Returns a short recap of requested endpoint (method + url) for logging. |
| 160 | + */ |
| 161 | +export function dbgRequestEndpoint(req: Request) { |
| 162 | + return `${req.method} ${req.url}` |
| 163 | +} |
| 164 | + |
| 165 | +/** |
| 166 | + * Returns an object based off Request reduced to the valuable information. |
| 167 | + */ |
| 168 | +export function dbgRequestObject(req: Request) { |
| 169 | + return { |
| 170 | + // full request URL (e.g. /mirror/1?test=2&tester=3) |
| 171 | + url: req.url, |
| 172 | + // query params (e.g. {test: 2, tester: 3}) |
| 173 | + query: req.query, |
| 174 | + // path (e.g. /mirror/1) |
| 175 | + path: req.path, |
| 176 | + // params (e.g. {id: 1}) |
| 177 | + params: req.params, |
| 178 | + // body (JSON, e.g. when POST requesting) |
| 179 | + body: req.body, |
| 180 | + } |
| 181 | +} |
0 commit comments