0
# Data Generation
1
2
Core template-based data generation system that creates realistic mock data using rule syntax and placeholders. Perfect for generating test data, API responses, and development fixtures.
3
4
## Capabilities
5
6
### Mock Function
7
8
The primary interface for generating mock data from templates.
9
10
```javascript { .api }
11
/**
12
* Generate mock data from a template
13
* @param template - Data template with optional generation rules
14
* @returns Generated mock data matching template structure
15
*/
16
Mock.mock(template: any): any;
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
// Simple placeholder
23
const name = Mock.mock('@name');
24
// Result: "William Anderson"
25
26
// Object template
27
const user = Mock.mock({
28
id: '@inc',
29
name: '@name',
30
email: '@email',
31
avatar: '@image(200x200)'
32
});
33
34
// Array with rules
35
const users = Mock.mock({
36
'data|5-10': [{
37
'id|+1': 1,
38
name: '@name',
39
'age|18-65': 1,
40
'status|1': ['active', 'inactive']
41
}]
42
});
43
```
44
45
### Template Rules
46
47
Rules control how data is generated and are specified using the `|` syntax after property names.
48
49
```javascript { .api }
50
// Array rules
51
'property|count': array // Repeat array items count times
52
'property|min-max': array // Generate min to max items
53
'property|1': array // Pick one item randomly
54
55
// String rules
56
'property|count': string // Repeat string count times
57
'property|min-max': string // Generate min to max length
58
59
// Number rules
60
'property|min-max': number // Generate number in range
61
'property|min-max.dmin-dmax': number // Float with decimal places
62
'property|+step': number // Auto-increment by step
63
64
// Boolean rules
65
'property|min-max': boolean // Probability ratio for true/false
66
'property|probability': boolean // Probability for current value
67
68
// Object rules
69
'property|count': object // Pick count properties randomly
70
'property|min-max': object // Pick min to max properties
71
```
72
73
**Rule Examples:**
74
75
```javascript
76
const data = Mock.mock({
77
// Array rules
78
'list|1-10': [{ name: '@name' }], // 1-10 items
79
'tags|3': ['javascript', 'node', 'web'], // Pick 3 tags
80
'categories|2-4': ['tech', 'business'], // 2-4 categories
81
82
// String rules
83
'stars|5': '★', // "★★★★★"
84
'code|4-8': 'A', // "AAAA" to "AAAAAAAA"
85
86
// Number rules
87
'age|18-65': 1, // Age between 18-65
88
'price|10-100.2-4': 1, // Price with 2-4 decimals
89
'id|+1': 1000, // Auto-increment from 1000
90
91
// Boolean rules
92
'active|3-1': true, // 3:1 ratio for true
93
'featured|1': false, // 1:1 ratio for false
94
95
// Object rules
96
'config|2-3': { // Pick 2-3 properties
97
debug: true,
98
logging: false,
99
cache: true,
100
compress: false
101
}
102
});
103
```
104
105
### Placeholders
106
107
Placeholders use the `@` syntax to generate specific types of random data.
108
109
```javascript { .api }
110
// Basic placeholders
111
'@boolean' // Random boolean
112
'@natural' // Natural number (>=0)
113
'@integer' // Integer
114
'@float' // Floating point number
115
'@character' // Single character
116
'@string' // Random string
117
118
// Parameterized placeholders
119
'@natural(min, max)' // Natural in range
120
'@integer(min, max)' // Integer in range
121
'@float(min, max, dmin, dmax)' // Float with decimal control
122
'@character(pool)' // Character from pool
123
'@string(pool, min, max)' // String from character pool
124
125
// Common data placeholders
126
'@name' // Full name
127
'@first' // First name
128
'@last' // Last name
129
'@email' // Email address
130
'@url' // URL
131
'@ip' // IP address
132
'@date' // Date string
133
'@time' // Time string
134
'@datetime' // DateTime string
135
'@image' // Image URL
136
'@color' // Color value
137
'@title' // Title text
138
'@sentence' // Sentence
139
'@paragraph' // Paragraph
140
'@guid' // GUID/UUID
141
```
142
143
**Placeholder Examples:**
144
145
```javascript
146
const profile = Mock.mock({
147
// Personal info
148
name: '@name', // "Sarah Johnson"
149
email: '@email', // "sarah.johnson@example.com"
150
avatar: '@image(100x100)', // Image URL
151
152
// Contact details
153
phone: '@natural(1000000000, 9999999999)',
154
address: '@city @county', // "Los Angeles County"
155
156
// Dates
157
birthday: '@date(yyyy-MM-dd)', // "1985-07-23"
158
loginTime: '@datetime', // "2023-04-15 14:30:22"
159
160
// Content
161
bio: '@sentence(10, 20)', // 10-20 word sentence
162
notes: '@paragraph(2, 4)', // 2-4 sentence paragraph
163
164
// IDs
165
userId: '@guid', // UUID
166
sessionId: '@string(upper, 8)', // 8 character uppercase
167
});
168
```
169
170
### Handler Module
171
172
Internal data template processing engine (available as `Mock.Handler`).
173
174
```javascript { .api }
175
Mock.Handler: {
176
/**
177
* Generate data from template (internal entry point)
178
* @param template - Data template
179
* @param name - Property name for context
180
* @param context - Generation context
181
* @returns Generated data
182
*/
183
gen(template: any, name?: string, context?: any): any;
184
185
/**
186
* Extend objects (utility function)
187
* @param target - Target object
188
* @param sources - Source objects to merge
189
* @returns Extended target object
190
*/
191
extend(target: any, ...sources: any[]): any;
192
193
// Internal type handlers (for advanced usage)
194
array(options: HandlerOptions): any[];
195
object(options: HandlerOptions): any;
196
number(options: HandlerOptions): number;
197
boolean(options: HandlerOptions): boolean;
198
string(options: HandlerOptions): string;
199
200
/**
201
* Process data placeholders (@name, @email, etc.)
202
* @param placeholder - Placeholder string
203
* @param obj - Current object context
204
* @param templateContext - Template context
205
* @param options - Handler options
206
* @returns Generated placeholder value
207
*/
208
placeholder(placeholder: string, obj: any, templateContext: any, options: HandlerOptions): any;
209
210
/**
211
* Get value by key path for template references
212
* @param key - Key path (e.g., 'user.id', '../name')
213
* @param options - Handler options with context
214
* @returns Value at key path
215
*/
216
getValueByKeyPath(key: string, options: HandlerOptions): any;
217
218
/**
219
* Normalize path array for consistent path handling
220
* @param pathParts - Array of path components
221
* @returns Normalized path array
222
*/
223
normalizePath(pathParts: string[]): string[];
224
225
/**
226
* Split path string into array components
227
* @param path - Path string (e.g., 'user.profile.name')
228
* @returns Array of path components
229
*/
230
splitPathToArray(path: string): string[];
231
}
232
233
interface HandlerOptions {
234
type: string;
235
template: any;
236
name?: string;
237
parsedName?: string;
238
rule?: any;
239
context?: any;
240
}
241
```
242
243
### Generation Context
244
245
Advanced usage with custom context and template references.
246
247
```javascript { .api }
248
// Relative references
249
const template = {
250
user: {
251
id: '@inc',
252
name: '@name',
253
email: '@email'
254
},
255
posts: [{
256
authorId: '@user.id', // Reference user.id
257
title: '@title',
258
content: '@paragraph'
259
}]
260
};
261
262
// Function templates
263
const data = Mock.mock({
264
timestamp: () => Date.now(),
265
computed: function() {
266
return this.id * 2; // Access current context
267
}
268
});
269
```
270
271
### Advanced Template Patterns
272
273
Complex real-world examples combining multiple features:
274
275
```javascript
276
// E-commerce product catalog
277
const productCatalog = Mock.mock({
278
'categories|3-5': [{
279
'id|+1': 1,
280
name: '@title(1, 3)',
281
slug: '@string(lower, 5, 12)',
282
'products|5-15': [{
283
'id|+1': 1000,
284
name: '@title(2, 5)',
285
'price|9.99-999.99': 1,
286
'inStock|3-1': true,
287
'rating|1-5.1': 1,
288
'reviews|0-50': 1,
289
description: '@paragraph(1, 3)',
290
images: {
291
'thumbnail': '@image(150x150)',
292
'gallery|2-5': ['@image(400x400)']
293
},
294
'tags|1-4': ['electronics', 'gadget', 'premium', 'bestseller', 'new']
295
}]
296
}],
297
298
// Pagination info
299
meta: {
300
total: '@natural(100, 1000)',
301
'page|1-10': 1,
302
'perPage|10': 1,
303
hasMore: '@boolean'
304
}
305
});
306
307
// User activity log
308
const activityLog = Mock.mock({
309
userId: '@guid',
310
'activities|10-50': [{
311
'id|+1': 1,
312
'type|1': ['login', 'logout', 'purchase', 'view', 'search'],
313
timestamp: '@datetime(yyyy-MM-dd HH:mm:ss)',
314
'data': function() {
315
// Dynamic data based on activity type
316
const types = {
317
login: { ip: '@ip', device: '@string(lower, 5, 10)' },
318
purchase: { amount: '@float(10, 500, 2, 2)', productId: '@natural(1, 1000)' },
319
search: { query: '@sentence(1, 4)', results: '@natural(0, 100)' },
320
view: { pageUrl: '@url', duration: '@natural(5, 300)' }
321
};
322
return types[this.type] || {};
323
}
324
}]
325
});
326
327
// Nested relational data
328
const blogData = Mock.mock({
329
'authors|3-8': [{
330
'id|+1': 1,
331
name: '@name',
332
email: '@email',
333
avatar: '@image(64x64)',
334
'followers|0-1000': 1
335
}],
336
337
'posts|15-30': [{
338
'id|+1': 100,
339
title: '@title(3, 8)',
340
slug: '@string(lower, 10, 20)',
341
'authorId|1-8': 1, // References author IDs
342
content: '@paragraph(5, 15)',
343
'publishedAt': '@date(yyyy-MM-dd)',
344
'status|1': ['draft', 'published', 'archived'],
345
'viewCount|0-10000': 1,
346
347
'comments|0-25': [{
348
'id|+1': 1000,
349
author: '@name',
350
email: '@email',
351
content: '@sentence(5, 30)',
352
createdAt: '@datetime',
353
'approved|7-3': true
354
}],
355
356
'tags|1-5': ['javascript', 'web', 'tutorial', 'nodejs', 'react', 'vue', 'angular']
357
}]
358
});
359
```