基本使用
介绍
DataFaker使用起来十分的简单,你只需要:
- 定义数据模型
- 生成数据
定义模型-defineModel
defineModel方法用于定义数据模型,它接受两个参数:
- 模型名称
- 数据模板
数据模板是一个对象,键名为字段名,其详情参见模板语法
ts
// 定义模型
const userModel = defineModel('user', {
id: 'string.uuid',
name: 'person.fullName',
age: ['number.int', { min: 18, max: 30 }],
});生成数据-fakeData
使用fakeData函数并传入数据模型就能生成模型模板对象的数据,如下所示:
ts
// 生成数据
const data = fakeData(userModel);
console.log(data);生成的数据如下:
json
{
"id": "5bdfc8e5-3b33-4560-b4ca-8b32b0150661",
"name": "Malcolm Simonis",
"age": 18
}第二个参数
实际上fakeData函数还可以接受第二个参数options,用于进行运行时配置,如下所示:
ts
/**
* 使用模型配置
*/
type DataFakeOptions = {
/**
* 生成数量
*/
count?: number;
/**
* 对于引用类型的规则
*/
refRules?: RefModelRule;
/**
* 钩子函数
*/
hooks?: DataFakeHook;
/**
* 语言环境
*/
locale?: LocaleType;
};ts
/**
* Fake数据规则
*/
type RefModelRule = {
/**
* 生成数量
*/
[COUNT]?: number;
/**
* 引用自身时的递归深度
*/
[DEEP]?: number;
/**
* 结构递归
*/
[key: string | symbol]: number | RefModelRule | [number, number];
};ts
/**
* schema类型
*/
type SchemaType = 'function' | 'object' | 'array' | 'string';
/**
* beforeEachCbs的上下文对象
*/
type BeforeEachContext = {
/**
* 每次循环的key
*/
key: string | symbol;
/**
* schema
*/
schema: DataFieldType;
/**
* 模板schema的类型
*/
type: SchemaType;
/**
* 所属对象
*/
belongTo: string | symbol;
};
/**
* afterEachCbs的上下文对象
*/
type AfterEachContext = {
/**
* 每次循环的key
*/
key: string | symbol;
/**
* 每次循环后的value
*/
value: any;
/**
* 已经生成的数据结果
*/
result: any;
/**
* 模板schema的类型
*/
type: SchemaType;
/**
* 所属对象
*/
belongTo: string | symbol;
};
/**
* 数据生成钩子
*/
type DataFakeHook = {
/**
* 数据生成前的钩子
*/
beforeAllCbs?: DataFakeCb<ModelSchema>;
/**
* 数据生成之后的钩子
*/
afterAllCbs?: DataFakeCb;
/**
* 每次循环之前的钩子
*/
beforeEachCbs?: DataFakeCb<BeforeEachContext>;
/**
* 每次循环生成数据之后的钩子
*/
afterEachCbs?: DataFakeCb<AfterEachContext>;
};
/**
* 数据生成后的回调函数类型
*/
type DataFakeCb<T = any> = ((data: T) => T) | Array<(data: T) => T>;ts
/**
* 语言环境类型
*/
type LocaleType = AllFakers | Array<LocaleDefinition | AllFakers> | Faker;具体来讲就是说可以在生成数据的时候,指定:
- 本身数据的生成数量
- 引用数据的生成数量
- 自引用数据的生成数量和递归深度
- 钩子函数
- 语言环境