@tse-ian/jsonschema-napi-rs
v1.0.7
Published
Template project for writing node package with napi-rs
Downloads
13
Maintainers
Readme
jsonschema-napi-rs
基于 napi-rs 封装 Rust 的 jsonschema crate,为 Node/TypeScript 提供高性能的 JSON Schema 校验能力。
特性
- 一次性校验:isValid(schema, instance)
- 复用校验器:validatorFor(schema) 返回 Validator 以复用编译后的 schema
- 详细输出:
- Validator.isValid(instance):布尔校验
- Validator.iterErrors(instance):错误列表(message、instancePath、schemaLocation、evaluationPath)
- 自动生成 TypeScript 类型定义,直接在 TS 项目中使用
安装与本地构建
- 安装依赖:
yarn - 本地构建:
yarn build- 构建后将生成平台对应的
.node文件,index.js会自动按平台加载
- 构建后将生成平台对应的
快速使用
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,
}
// 一次性校验
console.log(isValid(schema, { a: 1 })) // true
// 复用校验器
const v = validatorFor(schema)
console.log(v.isValid({ a: 2 })) // true
console.log(v.iterErrors({ a: 'x' }))
// [ { message, instancePath, schemaLocation, evaluationPath }, ... ]TypeScript 类型(自动生成)见 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): Validator性能对比
以下对比来自本仓库的基准测试(详见 benchmark/bench.ts),展示原生实现与纯 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 │
└─────────┴─────────────────────────────────┴──────────────────┴──────────────────┴────────────────────────┴────────────────────────┴─────────┘在多次校验场景下,使用 validatorFor 复用已编译的 schema 可进一步提升性能与吞吐。
运行基准测试
- 运行命令:
yarn bench - 脚本位置:
benchmark/bench.ts
开发脚本
- 构建:
yarn build(发布构建) /yarn build:debug(调试) - 格式化:
yarn format - 代码检查:
yarn lint
关键文件
- Rust 实现:src/lib.rs
- 类型定义:index.d.ts
- 入口加载:index.js
- 构建与脚本:package.json
许可证
MIT
