A Rust jsonschema crate wrapper based on napi-rs, providing high-performance JSON Schema validation capabilities for Node.js/TypeScript.
- One-time validation:
isValid(schema, instance) - Reusable validator:
validatorFor(schema)returns aValidatorto reuse the compiled schema - Detailed output:
Validator.isValid(instance): Boolean validation resultValidator.iterErrors(instance): Error list (message,instancePath,schemaLocation,evaluationPath)
- Automatically generated TypeScript type definitions for direct use in TS projects
- Install dependencies:
yarn - Local build:
yarn build- After building, a platform-specific
.nodefile will be generated, andindex.jswill automatically load the appropriate file for the platform.
- After building, a platform-specific
npm install @tse-ian/jsonschema-napi-rs@latestconst { isValid, validatorFor } = require('@tse-ian/jsonschema-napi-rs')
const schema = {
type: 'object',
properties: {
a: { type: 'number' },
},
required: ['a'],
additionalProperties: false,
}
// One-time validation
console.log(isValid(schema, { a: 1 })) // true
// Reusable validator
const v = validatorFor(schema)
console.log(v.isValid({ a: 2 })) // true
console.log(v.iterErrors({ a: 'x' }))
// [ { message, instancePath, schemaLocation, evaluationPath }, ... ]TypeScript types (auto-generated) can be found in index.d.ts:
export interface ValidationErrorOut {
message: string
instancePath: string
schemaLocation: string
evaluationPath: string
}
export declare class Validator {
isValid(instance: any): boolean
iterErrors(instance: any): Array<ValidationErrorOut>
}
export declare function isValid(schema: any, instance: any): boolean
export declare function validatorFor(schema: any): ValidatorThe following comparison is based on the benchmark tests in this repository (see benchmark/bench.ts), showing the performance difference between the native implementation and pure JavaScript:
│ (index) │ Task name │ Latency avg (ns) │ Latency med (ns) │ Throughput avg (ops/s) │ Throughput med (ops/s) │ Samples │
├─────────┼─────────────────────────────────┼──────────────────┼──────────────────┼────────────────────────┼────────────────────────┼─────────┤
│ 0 │ 'Native validator.isValid' │ '15805 ± 7.38%' │ '13796 ± 498.00' │ '68601 ± 0.07%' │ '72485 ± 2686' │ 126542 │
│ 1 │ 'JavaScript Validator.validate' │ '38220 ± 0.63%' │ '34417 ± 855.00' │ '27453 ± 0.11%' │ '29055 ± 736' │ 52330 │
└─────────┴─────────────────────────────────┴──────────────────┴──────────────────┴────────────────────────┴────────────────────────┴─────────┘
In scenarios requiring multiple validations, using validatorFor to reuse a compiled schema can further improve performance and throughput.
- Run command:
yarn bench - Script location:
benchmark/bench.ts
- Build:
yarn build(release build) /yarn build:debug(debug build) - Format:
yarn format - Lint:
yarn lint
- Rust implementation: src/lib.rs
- Type definitions: index.d.ts
- Entry point loader: index.js
- Build configuration & scripts: package.json
MIT