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