|
| 1 | +import { InstallTabs } from '@site/src/components/InstallTabs'; |
| 2 | + |
| 3 | +# Express Server |
| 4 | + |
| 5 | +## Installation |
| 6 | + |
| 7 | +<InstallTabs packageName="@ts-rest/express" /> |
| 8 | + |
| 9 | +## Usage |
| 10 | + |
| 11 | +```typescript |
| 12 | +import { initServer } from '@ts-rest/express'; |
| 13 | +import { contract } from './contract'; |
| 14 | + |
| 15 | +const app = express(); |
| 16 | +app.use(bodyParser.urlencoded({ extended: false })); |
| 17 | +app.use(bodyParser.json()); |
| 18 | + |
| 19 | +const s = initServer(); |
| 20 | +const router = s.router(contract, { |
| 21 | + getPost: async ({ params: { id } }) => { |
| 22 | + const post = prisma.post.findUnique({ where: { id } }); |
| 23 | + |
| 24 | + return { |
| 25 | + status: 200, |
| 26 | + body: post ?? null, |
| 27 | + }; |
| 28 | + }, |
| 29 | +}); |
| 30 | + |
| 31 | +createExpressEndpoints(contract, router, app); |
| 32 | +``` |
| 33 | + |
| 34 | +`createExpressEndpoints` is a function that takes a contract, a corresponding router with implementations and middleware for each endpoint, and an express app, and it will |
| 35 | +create the corresponding express routes for each endpoint with the correct method, paths and middleware and attach them to your express app. |
| 36 | + |
| 37 | +## Options |
| 38 | + |
| 39 | +You can pass an optional options object as the last argument for `createExpressEndpoints`. |
| 40 | + |
| 41 | +```typescript |
| 42 | +type Options = { |
| 43 | + logInitialization?: boolean; // print route initialization logs to console |
| 44 | + jsonQuery?: boolean; |
| 45 | + responseValidation?: boolean; |
| 46 | + globalMiddleware?: ((req, res, next) => void)[]; |
| 47 | + requestValidationErrorHandler?: |
| 48 | + | 'default' |
| 49 | + | 'combined' |
| 50 | + | ((err: RequestValidationError, req, res, next) => void); |
| 51 | +}; |
| 52 | +``` |
| 53 | + |
| 54 | +### Response Validation |
| 55 | + |
| 56 | +To enable response parsing and validation, you can use the `validateResponses` option. |
| 57 | +If there is a corresponding response Zod schema defined in the contract for the returned status code, the response will be parsed and validated. |
| 58 | +If validation fails a `ResponseValidationError` will be thrown causing a 500 response to be returned. |
| 59 | + |
| 60 | +```typescript |
| 61 | +createExpressEndpoints(contract, router, app, { |
| 62 | + validateResponses: true, |
| 63 | +}); |
| 64 | +``` |
| 65 | + |
| 66 | +### Request Validation Error Handling |
| 67 | + |
| 68 | +The default functionality of handling request validation errors is to return a 400 response with the first validation error that the validator comes across. |
| 69 | + |
| 70 | +You can pass `combined` to the `requestValidationErrorHandler` option to return a 400 response with all validation errors in the body in this form. |
| 71 | + |
| 72 | +```typescript |
| 73 | +{ |
| 74 | + pathParameterErrors: z.ZodError | null; |
| 75 | + headerErrors: z.ZodError | null; |
| 76 | + queryParameterErrors: z.ZodError | null; |
| 77 | + bodyErrors: z.ZodError | null; |
| 78 | +} |
| 79 | +``` |
| 80 | + |
| 81 | +You can also pass a custom error handler function to the `requestValidationErrorHandler` option. |
| 82 | + |
| 83 | +```typescript |
| 84 | +createExpressEndpoints(contract, router, app, { |
| 85 | + requestValidationErrorHandler: (err, req, res, next) => { |
| 86 | + // err is typed as ^ RequestValidationError |
| 87 | + return res.status(400).json({ |
| 88 | + message: 'Validation failed' |
| 89 | + }); |
| 90 | + }, |
| 91 | +}); |
| 92 | +``` |
0 commit comments