Last active
October 1, 2023 03:21
-
-
Save esatterwhite/9fc6e3bf0ee4ef08b5063120f865bc3b to your computer and use it in GitHub Desktop.
Wonky fastify schema validation handling
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
'use strict' | |
const fastify = require('fastify') | |
const fluent = require('fluent-json-schema') | |
const WhizBang = fluent | |
.object() | |
.additionalProperties(false) | |
.id('whizbang') | |
.title('WhizBang') | |
.prop( | |
'whiz' | |
, fluent.string().required().minLength(1) | |
) | |
.prop( | |
'bang' | |
, fluent.string().required().minLength(1) | |
) | |
const server = fastify({ | |
ajv: { | |
customOptions: { | |
allErrors: true | |
} | |
} | |
}) | |
// Commenting this out will allow this to work as expected | |
// but openapi spec is missing schemas, and ref will not work | |
server.addSchema(WhizBang) | |
server | |
.register(require('@fastify/swagger'), { | |
routePrefix: '/oas' | |
, exposeRoute: true | |
, refResolver: { | |
buildLocalReference(json, baseUri, fragment, i) { | |
return json.$id || `my-fragment-${i}` | |
} | |
} | |
, openapi: { | |
openapi: '3.0.3' | |
, info: { | |
title: 'open api' | |
, description: 'open api documentation' | |
, version: 'v2' | |
} | |
, servers: [{ | |
url: 'http://localhost:3000' | |
}] | |
} | |
}) | |
.register(async function(fastify) { | |
fastify.post('/whizbang', { | |
schema: { | |
body: WhizBang.only('whiz') | |
, response: { | |
200: WhizBang | |
} | |
} | |
, handler: async function(req, reply) { | |
const body = req.body | |
return { | |
whiz: body.whiz, | |
bang: 'foobar' | |
} | |
} | |
}) | |
}) | |
server | |
.ready() | |
.then(() => { | |
return server.swagger() | |
}) | |
.then(() => { | |
return server.listen(3000) | |
}) | |
.catch((error) => { | |
process.nextTick(() => { | |
throw error | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment