Skip to content

Commit

Permalink
Merge pull request #266 from trojs/feature/custom-ajv-validator-v1
Browse files Browse the repository at this point in the history
Add option to customize the ajv validator
  • Loading branch information
w3nl authored Jan 24, 2025
2 parents 2914187 + 0db174a commit 9b4521a
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 63 deletions.
121 changes: 66 additions & 55 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@trojs/openapi-server",
"description": "OpenAPI Server",
"version": "1.6.1",
"version": "1.7.0",
"author": {
"name": "Pieter Wigboldus",
"url": "https://trojs.org/"
Expand Down Expand Up @@ -80,8 +80,8 @@
"url": "https://github.com/sponsors/w3nl"
},
"overrides": {
"semver": "^7.5.3",
"send": "^0.19.0",
"semver@<=7.5.3": "^7.5.3",
"send@<=0.19.0": "^0.19.0",
"cookie@<=0.7.0": "0.7.0"
}
}
12 changes: 8 additions & 4 deletions src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { unauthorized } from './handlers/unauthorized.js'
* @typedef {import('./api.js').SecurityHandler} SecurityHandler
* @typedef {import('./api.js').Handler} Handler
* @typedef {import('ajv').Options} AjvOpts
* @typedef {import('openapi-backend').AjvCustomizer} AjvCustomizer
*/

/**
Expand All @@ -27,6 +28,7 @@ import { unauthorized } from './handlers/unauthorized.js'
* @param {SecurityHandler[]=} params.securityHandlers
* @param {Handler=} params.unauthorizedHandler
* @param {AjvOpts=} params.ajvOptions
* @param {AjvCustomizer=} params.customizeAjv
* @param {boolean=} params.mock
* @returns {{ api: OpenAPIBackend<any>, openAPISpecification: object }}
*/
Expand All @@ -41,17 +43,19 @@ export const setupRouter = ({
securityHandlers = [],
unauthorizedHandler,
ajvOptions = {},
customizeAjv,
mock
}) => {
const ajvWithExtraFormats = (originalAjv) => {
addFormats(originalAjv)
return originalAjv
}
const api = new OpenAPIBackend({
definition: openAPISpecification,
apiRoot,
strict: strictSpecification,
ajvOpts: ajvOptions,
customizeAjv: (originalAjv) => {
addFormats(originalAjv)
return originalAjv
}
customizeAjv: customizeAjv || ajvWithExtraFormats
})

api.register({
Expand Down
9 changes: 8 additions & 1 deletion src/router.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,14 @@ test('Test the router', async (t) => {
const { api } = setupRouter({
secret: envExample.SECRET,
openAPISpecification,
controllers
controllers,
customizeAjv: (originalAjv) => {
originalAjv.addKeyword('example', {
validate: (schema, data) => data === 'example',
errors: false
})
return originalAjv
}
})
const context = {
response: {
Expand Down

0 comments on commit 9b4521a

Please sign in to comment.