Created
July 5, 2023 03:10
-
-
Save scarf005/144392bb9b7ca43ff684801cd0966ff5 to your computer and use it in GitHub Desktop.
inferring responses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { initContract, ServerInferResponseBody, ServerInferResponses } from "npm:@ts-rest/core" | |
import z, { boolean } from "npm:zod" | |
import { createExpressEndpoints, initServer } from "npm:@ts-rest/express" | |
// @deno-types=npm:@types/express | |
import express from "npm:express" | |
const dataSchema = z.object({ data: z.boolean().default(false) }) | |
type DataInfer = z.infer<typeof dataSchema> | |
type DataInput = z.input<typeof dataSchema> | |
type DataOutput = z.output<typeof dataSchema> | |
const c = initContract() | |
const contract = c.router( | |
{ | |
postData: { | |
method: "POST", | |
path: "/", | |
body: dataSchema, | |
responses: { 200: dataSchema }, | |
}, | |
}, | |
{ strictStatusCodes: true }, | |
) | |
type Responses = ServerInferResponses<typeof contract.postData> | |
const s = initServer() | |
const router = s.router(contract, { | |
postData: ({ body }) => { | |
console.log({ body }) | |
return Promise.resolve({ status: 200, body: { data: undefined } }) | |
}, | |
}) | |
const app = express() | |
app.use(express.json()) | |
createExpressEndpoints(contract, router, app, { | |
requestValidationErrorHandler: "combined", | |
responseValidation: true, | |
}) | |
app.listen(10000, () => console.log("Listening on port 10000")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment