1interface Schema {
2 type: string;
3 description: string;
4 properties?: Record<string, Schema>;
5 required?: string[];
6 items?: Schema;
7 maxLength?: number;
8 minLength?: number;
9}
10type TObject<T> = Record<string | number | symbol, T>;
11type MockHandlerMap = {
12 string: () => string;
13 number: () => number;
14 boolean: () => boolean;
15 array: () => any[];
16 object: () => {};
17};
json schema 生成器
类型声明
1function jsonSchemaGenerator(data: TObject<any>): Schema;
参数
必填 | 参数 | 说明 | 类型 | 默认值 |
---|---|---|---|---|
* | data | 数据 | TObject<any> |
返回值: Schema
示例
1import { jsonSchemaGenerator } from '@cmtlyt/json-schema';
2
3jsonSchemaGenerator({
4 name: 'John',
5 age: 30,
6 address: {
7 city: 'New York',
8 street: 'Wall Street',
9 },
10});
11/*
12{
13 type: 'object',
14 description: '',
15 required: ['name', 'age', 'address'],
16 properties: {
17 name: {
18 type: 'string',
19 description: '',
20 },
21 age: {
22 type: 'number',
23 description: '',
24 },
25 address: {
26 type: 'object',
27 description: '',
28 required: ['city', 'street'],
29 properties: {
30 city: {
31 type: 'string',
32 description: '',
33 },
34 street: {
35 type: 'string',
36 description: '',
37 },
38 },
39 },
40 },
41}
42*/
验证数据是否符合 schema
类型声明
1const verifyBySchema: (
2 schema: Schema,
3 data: TObject<any>,
4) => Promise<[boolean, { path: string; message: string }[] | null]>;
参数
必填 | 参数 | 说明 | 类型 | 默认值 |
---|---|---|---|---|
* | schema | schema | Schema | |
* | data | 数据 | TObject<any> |
返回值: Promise<[boolean, { path: string; message: string }[] | null]>
示例
1import { verifyBySchema } from '@cmtlyt/json-schema';
2
3verifyBySchema(
4 {
5 type: 'object',
6 properties: {
7 name: {
8 type: 'string',
9 },
10 age: {
11 type: 'number',
12 },
13 },
14 },
15 {
16 name: 'John',
17 age: 30,
18 },
19);
20/*
21[ true, null ]
22*/
23
24verifyBySchema(
25 {
26 type: 'object',
27 properties: {
28 name: {
29 type: 'string',
30 },
31 age: {
32 type: 'number',
33 },
34 },
35 },
36 {
37 name: 123,
38 age: '30',
39 },
40);
41/*
42[ false, [
43 {
44 path: '/name',
45 message: 'Expected type string but got number',
46 },
47 {
48 path: '/age',
49 message: 'Expected type number but got string',
50 },
51] ]
根据 schema 生成 mock 数据
类型声明
1function mockFromSchema(schema: Schema, handlerMap?: Partial<MockHandlerMap>): any;
参数
必填 | 参数 | 说明 | 类型 | 默认值 |
---|---|---|---|---|
* | schema | schema | Schema | |
handlerMap | 类型处理器 | Partial<MockHandlerMap> |
返回值: any
示例
1import { mockFromSchema } from '@cmtlyt/json-schema';
2
3mockFromSchema({
4 type: 'object',
5 properties: {
6 name: {
7 type: 'string',
8 },
9 age: {
10 type: 'number',
11 },
12 },
13});
14/*
15{
16 name: '',
17 age: 0,
18}
19*/
20
21mockFromSchema(
22 {
23 type: 'object',
24 properties: {
25 name: {
26 type: 'string',
27 },
28 age: {
29 type: 'number',
30 },
31 },
32 },
33 {
34 string: () => 'mock',
35 },
36);
37/*
38{
39 name: 'mock',
40 age: 0,
41}
42*/