UNPKG

typea

Version:

JS 数据结构验证、转换器

45 lines (44 loc) 1.11 kB
import { Type } from './createType.js'; import types from './types.js'; import { entry } from './router.js'; export * from './common.js'; export * from './types.js'; export * as Utility from './utility.js'; class Schema { static types = types; node; constructor(node) { this.node = node; } /** * @param entity 需要验证的数据 */ verify(entity) { const { error, data } = entry(this.node, entity); if (error) { const [point] = error; if (point === '.') { return { error: error.slice(1) }; } else { return { error }; } } else { return { value: data, data }; } } } export { Schema, types }; /** * 添加自定义数据类型 * @param name 数据类型名称 * @param methods 扩展方法 */ export function createType(name, methods) { if (typeof name !== 'string') { throw new Error(`name 参数必须为 string 类型`); } return types[name] = Type(name, methods); } export default Schema;