Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validator accepting plugins #552

Merged
merged 4 commits into from
Aug 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions packages/validator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ response to the user.

It can also be used in combination with [`httpcontentnegotiation`](#httpContentNegotiation) to load localised translations for the error messages (based on the currently requested language). This feature uses internally [`ajv-i18n`](http://npm.im/ajv-i18n) module, so reference to this module for options and more advanced use cases. By default the language used will be English (`en`), but you can redefine the default language by passing it in the `ajvOptions` options with the key `defaultLanguage` and specifying as value one of the [supported locales](https://www.npmjs.com/package/ajv-i18n#supported-locales).

Also, this middleware accepts an object with plugins to be applied to customize the internal `ajv` instance. Out-of-the-box, `ajv-i18n`, `ajv-errors` and `ajv-keywords` are being used.

## Install

Expand All @@ -57,8 +58,9 @@ npm install --save @middy/validator
to validate the input (`handler.event`) of the Lambda handler.
- `outputSchema` (object) (optional): The JSON schema object that will be used
to validate the output (`handler.response`) of the Lambda handler.
- `ajvOptions` (object) (optional): Options to pass to [ajv](https://epoberezkin.github.io/ajv/)
class constructor. Defaults are `{v5: true, coerceTypes: 'array', $data: true, allErrors: true, useDefaults: true, defaultLanguage: 'en'}`
- `ajvOptions` (object) (optional): Options to pass to [ajv](https://ajv.js.org)
class constructor. Defaults are `{v5: true, coerceTypes: 'array', $data: true, allErrors: true, useDefaults: true, defaultLanguage: 'en', jsonPointers: true}`. Note that `jsonPointers` is needed by `ajv-errors`.
- `ajvPlugins` (object) (optional): Plugin names (without `ajv-` preffix) as key and its options for the value, to apply to [ajv](https://ajv.js.org) once intantiated. Defaults are `{keywords: null, errors: null, i18n: null}`. Note that for no options `null` is used as value.


## Sample usage
Expand Down Expand Up @@ -131,6 +133,38 @@ handler({}, {}, (err, response) => {
})
```

Example for plugins applied with `ajv-bsontype`:

```javascript
const middy = require('@middy/core')
const validator = require('@middy/validator')

const handler = middy((event, context, cb) => {
cb(null, {})
})

const schema = {
required: ["name", "gpa"],
properties: {
name: {
bsonType: "string"
},
gpa: {
bsonType: [ "double" ]
}
}
}

handler.use(validator({ inputSchema: schema, ajvPlugins: { bsontype: null } }))

// invokes the handler, note that property foo is string and should be integer
const event = {
body: JSON.stringify({ name: "Leo", gpa: "4" })
}
handler(event, {}, (err, response) => {
expect(err.details[0].message).toEqual('should be double got 4')
})
```

## Middy documentation and examples

Expand Down
70 changes: 70 additions & 0 deletions packages/validator/__tests__/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -241,4 +241,74 @@ describe('📦 Middleware Validator', () => {
}
})
})

describe('🔌 Ajv plugins setup', () => {
beforeEach(() => {
jest.resetModules()
})

test('It should use out-of-the-box ajv-errors plugin', async () => {
expect.assertions(2)

const schema = {
type: 'object',
required: ['foo'],
properties: {
foo: { type: 'integer' }
},
errorMessage: 'should be an object with an integer property foo only'
}

const validator = require('../')

const handler = middy((event, context, cb) => {
cb(null, {})
})

handler.use(validator({ inputSchema: schema }))

try {
await invoke(handler, { foo: 'a' })
} catch (err) {
expect(err.message).toEqual('Event object failed validation')
expect(err.details).toEqual(
expect.arrayContaining([
expect.objectContaining({ message: 'should be an object with an integer property foo only' })
])
)
}
})

test('It should apply added plugin bsontype', async () => {
expect.assertions(2)
const schema = {
required: ['name', 'gpa'],
properties: {
name: {
bsonType: 'string'
},
gpa: {
bsonType: ['double']
}
}
}

const handler = middy((event, context, cb) => {
cb(null, {})
})

handler.use(validator({ inputSchema: schema, ajvPlugins: { bsontype: null } }))

try {
await invoke(handler, { name: 'Leo', gpa: '4' })
} catch (err) {
expect(err.message).toEqual('Event object failed validation')
expect(err.details).toEqual(
expect.arrayContaining([
expect.objectContaining({ message: 'should be double got 4' })
])
)
}
})
})
})
1 change: 1 addition & 0 deletions packages/validator/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ interface IValidatorOptions {
inputSchema?: any;
outputSchema?: any;
ajvOptions?: Partial<AjvOptions>;
ajvPlugins?: object;
}

declare const validator : middy.Middleware<IValidatorOptions, any, any>
Expand Down
40 changes: 27 additions & 13 deletions packages/validator/index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
const createError = require('http-errors')
const Ajv = require('ajv')
const ajvKeywords = require('ajv-keywords')
const ajvLocalize = require('ajv-i18n')
const { deepStrictEqual } = require('assert')

let ajv
let previousConstructorOptions
const defaults = {
const optionsDefault = {
v5: true,
coerceTypes: 'array', // important for query string params
allErrors: true,
useDefaults: true,
$data: true, // required for ajv-keywords
defaultLanguage: 'en'
defaultLanguage: 'en',
jsonPointers: true
}
const pluginsInstances = {}
const pluginsDefault = {
keywords: null,
errors: null,
i18n: null
}

const availableLanguages = Object.keys(ajvLocalize)
let availableLanguages

/* in ajv-i18n Portuguese is represented as pt-BR */
const languageNormalizationMap = {
Expand All @@ -38,9 +43,10 @@ const chooseLanguage = ({ preferredLanguage }, defaultLanguage) => {
return defaultLanguage
}

module.exports = ({ inputSchema, outputSchema, ajvOptions }) => {
const options = Object.assign({}, defaults, ajvOptions)
lazyLoadAjv(options)
module.exports = ({ inputSchema, outputSchema, ajvOptions, ajvPlugins }) => {
const options = Object.assign({}, optionsDefault, ajvOptions)
const pluginsOptions = Object.assign({}, pluginsDefault, ajvPlugins)
lazyLoadAjv(options, pluginsOptions)

const validateInput = inputSchema ? ajv.compile(inputSchema) : null
const validateOutput = outputSchema ? ajv.compile(outputSchema) : null
Expand All @@ -57,7 +63,7 @@ module.exports = ({ inputSchema, outputSchema, ajvOptions }) => {
const error = new createError.BadRequest('Event object failed validation')
handler.event.headers = Object.assign({}, handler.event.headers)
const language = chooseLanguage(handler.event, options.defaultLanguage)
ajvLocalize[language](validateInput.errors)
pluginsInstances.i18n[language](validateInput.errors)

error.details = validateInput.errors
throw error
Expand All @@ -84,9 +90,9 @@ module.exports = ({ inputSchema, outputSchema, ajvOptions }) => {
}
}

function lazyLoadAjv (options) {
function lazyLoadAjv (options, plugins) {
if (shouldInitAjv(options)) {
initAjv(options)
initAjv(options, plugins)
}

return ajv
Expand All @@ -106,9 +112,17 @@ function areConstructorOptionsNew (options) {
return false
}

function initAjv (options) {
function initAjv (options, pluginsOptions) {
ajv = new Ajv(options)
ajvKeywords(ajv)

Object.keys(pluginsOptions).forEach(p => {
pluginsInstances[p] = require(`ajv-${p}`)
if (typeof pluginsInstances[p] === 'function') {
pluginsInstances[p](ajv, pluginsOptions[p])
}
})

availableLanguages = Object.keys(pluginsInstances.i18n)

previousConstructorOptions = options
}
35 changes: 11 additions & 24 deletions packages/validator/package-lock.json

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

2 changes: 2 additions & 0 deletions packages/validator/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,14 @@
"dependencies": {
"@types/http-errors": "^1.6.1",
"ajv": "^6.5.0",
"ajv-errors": "^1.0.1",
"ajv-i18n": "^3.3.0",
"ajv-keywords": "^3.2.0",
"http-errors": "^1.6.3"
},
"devDependencies": {
"@middy/core": "^1.2.0",
"ajv-bsontype": "^1.0.7",
"es6-promisify": "^6.0.2"
},
"gitHead": "7a6c0fbb8ab71d6a2171e678697de9f237568431"
Expand Down