Skip to content

Instantly share code, notes, and snippets.

@adrienjoly
Last active August 21, 2022 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrienjoly/412c283b72dd648b256ed590283caa0c to your computer and use it in GitHub Desktop.
Save adrienjoly/412c283b72dd648b256ed590283caa0c to your computer and use it in GitHub Desktop.
Fastify server with payload validation, using TypeBox and Ajv.
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