Express Server
Installation
- npm
- yarn
- pnpm
npm install @ts-rest/express
yarn add @ts-rest/express
pnpm add @ts-rest/express
Usage
import { initServer } from '@ts-rest/express';
const s = initServer();
const router = s.router(router, {
getPost: async ({ params: { id } }) => {
const post = prisma.post.findUnique({ where: { id } });
return {
status: 200,
body: post ?? null,
};
},
});
createExpressEndpoints(router, completeRouter, app);
createExpressEndpoints
is a function that takes a router and a complete router, and creates endpoints, with the correct methods, paths and callbacks.
JSON Query Parameters
To handle JSON query parameters, you can use the jsonQuery
option.
createExpressEndpoints(router, completeRouter, app, { jsonQuery: true });
Response Validation
To enable response parsing and validation, you can use the validateResponses
option.
If there is a corresponding response Zod schema defined in the contract for the returned status code, the response will be parsed and validated.
If validation fails a ResponseValidationError
will be thrown causing a 500 response to be returned.
createExpressEndpoints(router, completeRouter, app, {
validateResponses: true,
});