|
| 1 | +--- |
| 2 | +title: typescript-express |
| 3 | +--- |
| 4 | + |
| 5 | +import {Tabs} from 'nextra/components' |
| 6 | + |
| 7 | +# Using the `typescript-express` template |
| 8 | +The `typescript-express` template outputs scaffolding code that handles the following: |
| 9 | + |
| 10 | +- Building an express [Router](https://expressjs.com/en/5x/api.html#express.router) instance with all routes in the openapi specification |
| 11 | +- Generating typescript types and runtime schema parsers for all request parameters/bodies and response bodies, using [zod](https://zod.dev/) or [joi](https://joi.dev/) |
| 12 | +- Generating types for route implementations that receive strongly typed, runtime validated inputs and outputs |
| 13 | +- (Optionally) Actually starting the server and binding to a port |
| 14 | + |
| 15 | +See [integration-tests/typescript-express](https://github.com/mnahkies/openapi-code-generator/tree/main/integration-tests/typescript-express) for more samples. |
| 16 | + |
| 17 | + |
| 18 | +### Install dependencies |
| 19 | +First install the CLI and the required runtime packages to your project: |
| 20 | +```sh npm2yarn |
| 21 | +npm i --dev @nahkies/openapi-code-generator @types/express |
| 22 | +npm i @nahkies/typescript-express-runtime express zod |
| 23 | +``` |
| 24 | + |
| 25 | +See also [quick start](../../getting-started/quick-start) guide |
| 26 | + |
| 27 | +### Run generation |
| 28 | +<Tabs items={["OpenAPI3", "Typespec"]}> |
| 29 | + |
| 30 | + <Tabs.Tab> |
| 31 | + ```sh npm2yarn |
| 32 | + npm run openapi-code-generator \ |
| 33 | + --input ./openapi.yaml \ |
| 34 | + --input-type openapi3 \ |
| 35 | + --output ./src/generated \ |
| 36 | + --template typescript-express \ |
| 37 | + --schema-builder zod |
| 38 | + ``` |
| 39 | + </Tabs.Tab> |
| 40 | + <Tabs.Tab> |
| 41 | + ```sh npm2yarn |
| 42 | + npm run openapi-code-generator \ |
| 43 | + --input ./typespec.tsp \ |
| 44 | + --input-type typespec \ |
| 45 | + --output ./src/generated \ |
| 46 | + --template typescript-express \ |
| 47 | + --schema-builder zod |
| 48 | + ``` |
| 49 | + </Tabs.Tab> |
| 50 | + |
| 51 | +</Tabs> |
| 52 | + |
| 53 | +### Using the generated code |
| 54 | +Running the above will output three files into `./src/generated`: |
| 55 | + |
| 56 | +- `generated.ts` - exports a `createRouter` and `bootstrap` function, along with associated types used to create your server |
| 57 | +- `models.ts` - exports typescript types for schemas |
| 58 | +- `schemas.ts` - exports runtime schema validators |
| 59 | + |
| 60 | +Once generated usage should look something like this: |
| 61 | + |
| 62 | +```typescript |
| 63 | +import {bootstrap, createRouter, CreateTodoList, GetTodoLists} from "../generated" |
| 64 | + |
| 65 | +// Define your route implementations as async functions implementing the types |
| 66 | +// exported from generated.ts |
| 67 | +const createTodoList: CreateTodoList = async ({body}, respond) => { |
| 68 | + const list = await prisma.todoList.create({ |
| 69 | + data: { |
| 70 | + // body is strongly typed and parsed at runtime |
| 71 | + name: body.name, |
| 72 | + }, |
| 73 | + }) |
| 74 | + |
| 75 | + // the `respond` parameter is a strongly typed response builder that pattern matches status codes |
| 76 | + // to the expected response schema. |
| 77 | + // the response body is validated against the response schema/status code at runtime |
| 78 | + return respond.with200().body(dbListToApiList(list)) |
| 79 | +} |
| 80 | + |
| 81 | +const getTodoLists: GetTodoLists = async ({query}) => { |
| 82 | + // omitted for brevity |
| 83 | +} |
| 84 | + |
| 85 | +// Starts a server listening on `port` |
| 86 | +bootstrap({ |
| 87 | + router: createRouter({getTodoLists, createTodoList}), |
| 88 | + port: 8080, |
| 89 | +}) |
| 90 | +``` |
| 91 | + |
| 92 | +### Multiple routers |
| 93 | +By default, a single router is generated, but for larger API surfaces this can become unwieldy. |
| 94 | + |
| 95 | +You can split the generated routers by using the [--grouping-strategy](/reference/cli-options#--grouping-strategy-value-experimental) |
| 96 | +option to control the strategy to use for splitting output into separate files. Set to none for a single generated.ts file, one of: |
| 97 | + |
| 98 | +- none: don’t split output, yield single generated.ts (default) |
| 99 | +- first-tag: group operations based on their first tag |
| 100 | +- first-slug: group operations based on their first route slug/segment |
| 101 | + |
| 102 | +This can help to organize your codebase and separate concerns. |
| 103 | + |
| 104 | +### Custom Express app |
| 105 | + |
| 106 | +The provided `bootstrap` function has a limited range of options. For more advanced use-cases, |
| 107 | +such as `https` you will need to construct your own Express `app`, and mount the router returned by `createRouter`. |
| 108 | + |
| 109 | +The only real requirement is that you provide body parsing middleware mounted before the `router` that places |
| 110 | +a parsed request body on the `req.body` property. |
| 111 | + |
| 112 | +Eg: |
| 113 | +```typescript |
| 114 | +import {createRouter, CreateTodoList, GetTodoLists} from "../generated" |
| 115 | + |
| 116 | +import express from "express" |
| 117 | +import https from "https" |
| 118 | +import fs from "fs" |
| 119 | + |
| 120 | +const createTodoList: CreateTodoList = async ({body}, respond) => { /*omitted for brevity*/ } |
| 121 | +const getTodoLists: GetTodoLists = async ({query}, respond) => { /*omitted for brevity*/ } |
| 122 | + |
| 123 | +const app = express() |
| 124 | + |
| 125 | +// mount middleware to parse JSON request bodies onto `req.body` |
| 126 | +app.use(express.json()) |
| 127 | + |
| 128 | +// mount the generated router with our handler implementations injected |
| 129 | +const router = createRouter({getTodoLists, createTodoList}) |
| 130 | +app.use(router) |
| 131 | + |
| 132 | +// create the HTTPS server using the express app |
| 133 | +https |
| 134 | + .createServer( |
| 135 | + { |
| 136 | + key: fs.readFileSync("path/to/key.pem"), |
| 137 | + cert: fs.readFileSync("path/to/cert.pem"), |
| 138 | + }, |
| 139 | + app |
| 140 | + ) |
| 141 | + .listen(433) |
| 142 | +``` |
| 143 | + |
| 144 | +### Error Handling |
| 145 | + |
| 146 | +Any errors thrown during the request processing will be wrapped in `ExpressRuntimeError` objects, |
| 147 | +and tagged with the `phase` the error was thrown. |
| 148 | + |
| 149 | +```typescript |
| 150 | +class ExpressRuntimeError extends Error { |
| 151 | + cause: unknown // the originally thrown exception |
| 152 | + phase: "request_validation" | "request_handler" | "response_validation" |
| 153 | +} |
| 154 | +``` |
| 155 | + |
| 156 | +This allows for implementing catch-all error middleware for common concerns like failed request validation, |
| 157 | +or internal server errors. |
| 158 | + |
| 159 | +Eg: |
| 160 | +```typescript |
| 161 | +import {ExpressRuntimeError} from "@nahkies/typescript-express-runtime/errors" |
| 162 | +import {Request, Response, NextFunction} from "express" |
| 163 | + |
| 164 | +export async function genericErrorMiddleware(err: Error, req: Request, res: Response, next: NextFunction) { |
| 165 | + if (res.headersSent) { |
| 166 | + return next(err) |
| 167 | + } |
| 168 | + |
| 169 | + // if the request validation failed, return a 400 and include helpful |
| 170 | + // information about the problem |
| 171 | + if (ExpressRuntimeError.isExpressError(err) && err.phase === "request_validation") { |
| 172 | + res.status(400).json({ |
| 173 | + message: "request validation failed", |
| 174 | + meta: err.cause instanceof ZodError ? {issues: err.cause.issues} : {}, |
| 175 | + }) |
| 176 | + return |
| 177 | + } |
| 178 | + |
| 179 | + // return a 500 and omit information from the response otherwise |
| 180 | + logger.error("internal server error", err) |
| 181 | + res.status(500).json({ |
| 182 | + message: "internal server error", |
| 183 | + }) |
| 184 | +} |
| 185 | +``` |
| 186 | + |
| 187 | +You can configure the error handler through the `bootstrap` function using the `errorHandler` argument, |
| 188 | +or simplify mount directly to the express `app` yourself. |
| 189 | + |
| 190 | +### Escape Hatches - raw `req` / `res` handling |
| 191 | +For most JSON based API's you shouldn't need to reach for this, but there are sometime situations where the |
| 192 | +code generation tooling doesn't support something you need (see also [roadmap](/overview/roadmap) / [compatibility](/overview/compatibility)). |
| 193 | + |
| 194 | +Eg: response headers are not yet supported. |
| 195 | + |
| 196 | +To account for these situations, we pass the raw express `req` and `res` objects to your handler implementations, |
| 197 | +allowing you full control where its needed. |
| 198 | +```typescript |
| 199 | +const createTodoList: CreateTodoList = async ({body}, respond, req, res) => { |
| 200 | + res.setHeader("x-ratelimit-remaining", "100") |
| 201 | + // ...your implementation |
| 202 | + return respond.with200().body({ /* ... */ }) |
| 203 | + } |
| 204 | +``` |
| 205 | + |
| 206 | +It's also possible to skip response processing if needed by returning `ExpressRuntimeResponse.Skip` from your implementation. |
| 207 | +This allows you take complete control of the response. |
| 208 | +```typescript |
| 209 | +const getProfileImage: GetProfileImage = async ({body}, respond, req, res) => { |
| 210 | + res.setHeader("x-ratelimit-remaining", "100") |
| 211 | + res.status(200).send(Buffer.from([/*some binary file*/])) |
| 212 | + |
| 213 | + return ExpressRuntimeResponse.Skip |
| 214 | + } |
| 215 | +``` |
| 216 | + |
| 217 | +It should be seldom that these escape hatches are required, and overtime fewer and fewer situations will |
| 218 | +require them. |
0 commit comments