Last active
August 21, 2022 06:39
-
-
Save adrienjoly/412c283b72dd648b256ed590283caa0c to your computer and use it in GitHub Desktop.
Fastify server with payload validation, using TypeBox and Ajv.
This file contains 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 Ajv from "ajv" | |
import Fastify from "fastify" | |
import type { TypeBoxTypeProvider } from "@fastify/type-provider-typebox" | |
import type { Static } from "@sinclair/typebox" | |
import { Type } from "@sinclair/typebox" | |
export const payloadSchema = Type.Object({ | |
message: Type.String(), | |
}) | |
export type Payload = Static<typeof payloadSchema> | |
export const reqBodySchema = Type.Object({ | |
name: Type.String(), | |
payload: Type.Object({}), // we will validate this part programatically | |
}) | |
export type ReqBody = Static<typeof reqBodySchema> | |
const server = Fastify({ logger: true }).withTypeProvider<TypeBoxTypeProvider>() | |
server.addHook("preValidation", async (req) => { | |
req.log.warn({ body: req.body }, "[preValidation] body") // useful to troubleshoot validation errors, inspired by https://www.fastify.io/docs/latest/Reference/Logging/#usage | |
}) | |
server.post<{ Body: ReqBody }>( | |
"/", | |
{ schema: { body: reqBodySchema } }, | |
async ({ body }, reply) => { | |
const ajv = new Ajv() | |
if (!ajv.validate(payloadSchema, body.payload)) { | |
const errMessage = ajv.errorsText() | |
server.log.warn(`validation error: ${errMessage}`) | |
reply.statusCode = 400 | |
return { error: err.message } | |
} | |
// TODO: process the request | |
return { ok: true } | |
} | |
) | |
createServer() | |
.listen({ | |
port: process.env.PORT, | |
host: "0.0.0.0", // makes the server reachable to all interfaces, when running from from a Docker container | |
}) | |
.catch((err) => { | |
server.log.error(err) | |
process.exit(1) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment