{"id":13716324,"url":"https://github.com/igat64/micro-ajv","last_synced_at":"2025-04-30T07:33:29.229Z","repository":{"id":34864658,"uuid":"185217418","full_name":"igat64/micro-ajv","owner":"igat64","description":"An Ajv (Another JSON Schema Validator) middleware for Micro","archived":false,"fork":false,"pushed_at":"2023-01-03T21:09:33.000Z","size":808,"stargazers_count":5,"open_issues_count":12,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-10-10T22:39:16.357Z","etag":null,"topics":["ajv","json-schema","json-schema-validator","jsonschema","jsonschema-validator","micro","middleware","nodejs"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/igat64.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-05-06T14:52:16.000Z","updated_at":"2019-09-10T06:58:13.000Z","dependencies_parsed_at":"2023-01-15T09:40:28.217Z","dependency_job_id":null,"html_url":"https://github.com/igat64/micro-ajv","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/igat64%2Fmicro-ajv","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/igat64%2Fmicro-ajv/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/igat64%2Fmicro-ajv/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/igat64%2Fmicro-ajv/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/igat64","download_url":"https://codeload.github.com/igat64/micro-ajv/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224044633,"owners_count":17246439,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ajv","json-schema","json-schema-validator","jsonschema","jsonschema-validator","micro","middleware","nodejs"],"created_at":"2024-08-03T00:01:09.388Z","updated_at":"2024-11-12T02:01:43.988Z","avatar_url":"https://github.com/igat64.png","language":"JavaScript","funding_links":[],"categories":["Modules"],"sub_categories":["Middlewares"],"readme":"# micro-ajv\n\nAn [Ajv](https://github.com/epoberezkin/ajv) (Another [JSON Schema](https://json-schema.org/) Validator) middleware for [Micro](https://github.com/zeit/micro) to validate request body, url, query parameters and etc.\n\n[![CircleCI](https://circleci.com/gh/igat64/micro-ajv.svg?style=svg)](https://circleci.com/gh/igat64/micro-ajv)\n\n## Installation\n\n```bash\nnpm install --save micro-ajv\n```\n\n## Usage\n\nBy default, it validates request body and replies with 400 status code if validation fails.\n\n```js\nconst { send } = require('micro')\nconst microAjvValidation = require('micro-ajv')\n\nconst schema = { type: 'string', maxLength: 1024 }\nconst validate = microAjvValidation(schema)\n\nconst handler = (req, res) =\u003e send(res, 200, 'Ok')\n\nmodule.exports = validate(handler)\n```\n\n#### Middleware Options\n\nIt's possible to configure the middleware behavior by passing `options` object\n\n| Option        | Description                                                                                                                                                                                                                                           | Default                                           |\n| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- |\n| `ajv`         | Ajv [options](https://github.com/epoberezkin/ajv#options)                                                                                                                                                                                             | `{}`                                              |\n| `target`      | Path to data for validations (e.g. `query.accountId`). It validates request body by default                                                                                                                                                           | `\"body\"`                                          |\n| `errorMode`   | Enables change middleware behavior strategy when request validation fails. There are three possible modes: `reply` — respond with an error; `throw` — throw an exception; `inject` – call handler with injected validation errors to the `req` object | `\"reply\"`                                         |\n| `injectKey`   | Enables pass validation errors to the `req` object when error mode is `inject`                                                                                                                                                                        | `\"microAjvErrors\"`                                |\n| `createError` | Use this option if you need to change the default error object. As a first argument, it expects Ajv validation [errors](https://www.npmjs.com/package/ajv#validation-errors)                                                                          | `errors =\u003e micro.createError(400, 'Bad request')` |\n\n#### Examples\n\nValidate `req.url` and handle validation errors inside the handler:\n\n```js\nconst { send } = require('micro')\nconst microAjvValidation = require('micro-ajv')\n\nconst schema = { type: 'string', maxLength: 1024 }\nconst options = { target: 'url', errorMode: 'inject', injectKey: 'errors' }\nconst validate = microAjvValidation(schema, options)\n\nmodule.exports = validate((req, res) =\u003e {\n  console.error(req.errors)\n  send(res, 414, 'Request url is too long')\n})\n```\n\nValidate `req.body` and reply with a custom error if it fails\n\n```js\nconst { send } = require('micro')\nconst microAjvValidation = require('micro-ajv')\n\nconst schema = { type: 'string', maxLength: 1024 }\nconst options = {\n  createError: errors =\u003e\n    Object.assign(Error(errors.map(error =\u003e error.message)), { statusCode: 400 }),\n}\n\nconst validate = microAjvValidation(schema, options)\n\nconst handler = (req, res) =\u003e send(res, 200, 'Ok')\n\nmodule.exports = validate(handler)\n```\n\nSometime you may need to throw an exception and probably catch it somewhere else in the project instead of replying with an error immediately.\n\n```js\n// handler.js\nconst { send } = require('micro')\nconst microAjvValidation = require('micro-ajv')\n\nconst schema = { type: 'string', maxLength: 1024 }\nconst options = {\n  errorMode: 'throw',\n  createError: errors =\u003e\n    Object.assign(Error('Payload validation failed'), { type: 'ApiError', statusCode: 400 }),\n}\nconst validate = microAjvValidation(schema, options)\n\nconst handler = (req, res) =\u003e send(res, 200, 'Ok')\n\nmodule.exports = validate(handler)\n```\n\n```js\n// middleware.js\nmodule.exports.logApiErrors = handler =\u003e (req, res) =\u003e\n  handler(req, res).catch(err =\u003e {\n    if (err.type === 'ApiError') {\n      console.log(`ApiError: ${err.message}`)\n    }\n    throw err\n  })\n```\n\n```js\n// index.js\nconst { router, post } = require('microrouter')\nconst { logApiErrors } = require('./middleware')\nconst handler = require('./handler')\n\nmodule.exports = logApiErrors(router(post('/foo', handler)))\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Figat64%2Fmicro-ajv","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Figat64%2Fmicro-ajv","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Figat64%2Fmicro-ajv/lists"}