JsonSchemaValidator
SUPPORT · interface · 类型合同
App-owned JSON Schema compilers provide synchronous validation.
导入
ts
import type { JsonSchemaValidator } from '@jangts/agent-core/support';js
/** @typedef {import('@jangts/agent-core/support').JsonSchemaValidator} JsonSchemaValidator */其他公开入口:@jangts/agent-core/types、@jangts/agent-core/structs、@jangts/agent-core/support。
定义
ts
interface JsonSchemaValidator<Output>泛型参数
| 类型参数 | 约束 | 默认类型 |
|---|---|---|
Output | — | unknown |
调用
ts
JsonSchemaValidator(value: unknown): value is OutputReturns whether the value is valid; must be synchronous.
| 参数 | 类型 | 传递 | 说明 |
|---|---|---|---|
value | unknown | 必需 | — |
返回: boolean。
字段结构
| 字段 | 类型 | 必需 | 说明 |
|---|---|---|---|
errors | unknown | 可省略 | 只读。Compiler-reported details for the last failed validation, when the library exposes them. |
使用示例
- Schema:保留 JSON 声明与实际解析的同一合同:Support 生成规范的 SchemaAdapter,Core 只要求 jsonSchema 与同步 parse 合同。
一个有实际校验的字符串对象
入门 · Node.js
ts
import { Support } from '@jangts/agent-core';
const nameSchema = Support.defineSchema({
jsonSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'], additionalProperties: false },
parse(value: unknown) {
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length !== 1 || !('name' in value) || typeof value.name !== 'string') throw new TypeError('需要 name 字符串');
return { name: value.name };
},
});
console.log(nameSchema.parse({ name: 'Ivan' }));js
import { Support } from '@jangts/agent-core';
const nameSchema = Support.defineSchema({
jsonSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'], additionalProperties: false },
parse(value) {
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length !== 1 || !('name' in value) || typeof value.name !== 'string')
throw new TypeError('需要 name 字符串');
return { name: value.name };
},
});
console.log(nameSchema.parse({ name: 'Ivan' }));复用已经拥有的解析对象
配置 · Node.js
实际接解析库时,toJsonSchema 必须准确表达该 parser;不是库名称决定可信度。
ts
import { Support } from '@jangts/agent-core';
class NameParser {
parse(value: unknown) { if (typeof value !== 'string' || !value.trim()) throw new TypeError('需要非空姓名'); return value.trim(); }
}
const schema = Support.fromParserSchema(new NameParser(), {
toJsonSchema: () => ({ type: 'string', minLength: 1 }),
});
console.log(schema.parse(' Ivan '));js
import { Support } from '@jangts/agent-core';
class NameParser {
parse(value) { if (typeof value !== 'string' || !value.trim())
throw new TypeError('需要非空姓名'); return value.trim(); }
}
const schema = Support.fromParserSchema(new NameParser(), {
toJsonSchema: () => ({ type: 'string', minLength: 1 }),
});
console.log(schema.parse(' Ivan '));