metalman-schema
raw JSON → 4.0.2 verified Thu Apr 23 auth: no javascript
metalman-schema is a JSON schema validation middleware specifically designed for the `metalman` module. It leverages the `ajv` library for robust JSON schema validation. The current stable version is 4.0.2, released in November 2023, indicating an active but not rapid release cadence, with previous major updates in 2021. This library differentiates itself by providing a `metalman`-compatible middleware, allowing schema definitions to be integrated directly into `metalman` commands for streamlined request validation. It acts as a factory function that returns the actual middleware, providing flexibility to configure the underlying `ajv` instance.
Common errors
error err.name equals 'ValidationError' ↓
cause Input data to the metalman command does not conform to the defined JSON schema.
fix
Inspect
err.errors (if available) or err.message for details on which part of the input failed validation. Adjust the input data or refine the JSON schema definition. error TypeError: Cannot read properties of undefined (reading 'schema') ↓
cause The `metalman-schema` middleware expects the schema to be present on the `command` object (e.g., `command.schema`). This error occurs if the `schema` property is missing from the command options.
fix
Ensure that the
metalman command function, when called, receives an options object that includes a schema property with a valid JSON schema definition, e.g., commandFactory({ schema: { type: 'object', ... } }). error Ajv is not a constructor ↓
cause This usually indicates an incorrect import or version mismatch of `ajv`, especially after the v7 upgrade where `new Ajv()` syntax became mandatory and `require('ajv')` directly returns the constructor (or `require('ajv').default` for some setups).
fix
For
ajv v7+, use const Ajv = require('ajv').default; for CommonJS or import Ajv from 'ajv'; for ESM, then instantiate with new Ajv(). Ensure ajv is correctly installed. Warnings
breaking Version 4.0.0 introduced a breaking change by upgrading the underlying JSON schema validator to AJV v7. This might break existing schemas, particularly those using older draft specifications (like draft-04, which is no longer supported by AJV v7) or relying on removed keywords. ↓
fix Review AJV v7 release notes for schema migration guidelines, especially regarding `$id` vs `id` and format validation changes (now requiring `ajv-formats`). Update schemas to comply with JSON Schema draft-06 or later.
breaking Version 3.0.0 dropped support for `metalman@v2` and older Node.js versions, requiring an upgrade to `metalman@v3`. This version also mandates ES2015 features (e.g., `const` declarations). ↓
fix Ensure your project uses `metalman@v3` or newer and a Node.js version compatible with ES2015+ features. Update `require` statements to `const` for improved code style.
breaking Since version 3.0.0, the middleware automatically coerces types by default. This changes validation behavior, as values might be converted (e.g., '123' to 123) instead of failing validation for incorrect types. ↓
fix If type coercion is undesirable, you may need to configure the AJV instance passed to `createSchemaMiddleware` to disable this behavior (e.g., `{ coerceTypes: false }`). Refer to AJV documentation for exact options.
gotcha Since version 4.0.1, `ajv-formats` is automatically added by default if no custom `AJV` instance is passed to `createSchemaMiddleware`. If you were relying on a minimal AJV setup without format validation, this might introduce new validation rules for properties like `format: 'email'`. ↓
fix If you need to control format validation explicitly, pass a custom `AJV` instance to the `createSchemaMiddleware` factory and configure `ajv-formats` (or omit it) as per your requirements.
Install
npm install metalman-schema yarn add metalman-schema pnpm add metalman-schema Imports
- createSchemaMiddleware wrong
import { createSchemaMiddleware } from 'metalman-schema';correctimport createSchemaMiddleware from 'metalman-schema'; - createSchemaMiddleware wrong
const { factory } = require('metalman-schema');correctconst createSchemaMiddleware = require('metalman-schema'); - middleware wrong
const validate = require('metalman-schema'); // This gets the factory, not the middleware itselfcorrectconst validate = createSchemaMiddleware();
Quickstart
import metalman from 'metalman';
import createSchemaMiddleware from 'metalman-schema';
// Create the validation middleware using the factory
// You can pass ajvOptions or a custom ajv instance here: createSchemaMiddleware({ ajvOptions: { allErrors: true } })
const validate = createSchemaMiddleware();
// Define a metalman command with the validation middleware
const commandFactory = metalman([validate]);
const validateUser = commandFactory({
schema: {
type: 'object',
required: ['name', 'age'],
additionalProperties: false,
properties: {
name: { type: 'string', minLength: 1 },
age: { type: 'number', minimum: 18 }
}
}
});
// Valid case
validateUser({ name: 'Alice', age: 30 }, (err) => {
if (err) {
console.error('Validation failed for Alice:', err.message);
} else {
console.log('Validation successful for Alice.');
}
});
// Invalid case (age too low)
validateUser({ name: 'Bob', age: 16 }, (err) => {
if (err) {
console.error('Validation failed for Bob:', err.name, '-', err.message);
} else {
console.log('Validation successful for Bob.');
}
});
// Invalid case (missing required field)
validateUser({ age: 25 }, (err) => {
if (err) {
console.error('Validation failed (missing name):', err.name, '-', err.message);
} else {
console.log('Validation successful (missing name).');
}
});