Skip to content

Commit 903126a

Browse files
committed
Improve performance and error handling for getMocksGenerator
1 parent b2dceb5 commit 903126a

File tree

3 files changed

+22
-16
lines changed

3 files changed

+22
-16
lines changed

README.md

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
# Quick Mock Data Generator
22

3-
Need test data quickly? This lightweight utility helps you generate realistic mock data in seconds. Choose from common properties like names, emails, and dates, **or define your own generators**. Perfect for prototypes, tests, and demos where you need meaningful data fast.
3+
Need test data quickly? This utility helps you generate realistic mock data fast. Choose from common properties like names, emails, and dates, **or define your own generators**. Perfect for prototypes, tests, and demos where you need meaningful data right away.
44

55
Built on top of `@faker-js/faker`, it provides a simpler interface while maintaining type safety and full TypeScript support.
66

77
Key features:
88

99
- 🚀 Quick property selection from common data types
10-
- 🎯 Generate exactly what you need, nothing more
10+
- 🎯 Generate exactly what you decide, nothing more
1111
- 📦 Zero configuration required
1212
- 🔍 Full TypeScript support with autocompletion
1313

@@ -39,11 +39,9 @@ This basically returns a function that will create mock data based on a list of
3939
```typescript
4040
import { getMocksWith } from '@functions/mock'
4141

42-
// Autosuggestion will let you pick the properties you want in your mock objects
43-
const createRandomUsers = getMocksWith(['name', 'age', 'email'])
44-
45-
// Generate 3 users with only those properties
42+
const createRandomUsers = getMocksWith(['name', 'age', 'email']) // Autosuggestion helps you pick the props
4643
const users = createRandomUsers(3)
44+
//[ { name:"John", age: 64, email: "[email protected]" }, etc... ]
4745
```
4846

4947
### Generate Mock Data from a Generator
@@ -61,13 +59,9 @@ import { getMocksFromGenerator } from '@functions/mock'
6159
import { faker } from '@faker-js/faker'
6260

6361
const yourGenerator = {
64-
// Use faker functions directly
6562
id: faker.string.uuid,
66-
// Your own random logic
6763
age: () => Math.floor(Math.random() * (100 - 18 + 1)) + 18,
68-
// Mix calculated and faker values
6964
username: () => `user_${faker.number.int(1000)}`,
70-
// Fixed values
7165
role: () => 'user',
7266
// Complex custom logic
7367
status: () => {
@@ -77,9 +71,9 @@ const yourGenerator = {
7771
}
7872

7973
const createRandomObjects = getMocksFromGenerator(yourGenerator)
80-
// TypeScript should infers return types from your generator functions
74+
// TypeScript also infers return types from your generator functions
8175
const objects = createRandomObjects(5)
82-
// objects is typed as Array<{ id: string; name: string; age: number }>
76+
// [{ id: '...', age: 42, username: 'user_123', role: 'user', status: 'active' },
8377
```
8478

8579
## Contributing

utils/get-mocks-from-gen.ts

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,25 @@ type TMock = <T extends Record<string, () => any>>(g: T) => (n?: number) => { [K
88
* import { faker } from '@faker-js/faker'
99
* const yourGenerator = { name: faker.string.firstName, age: () => Math.floor(Math.random() * 100 ) }
1010
* const yourObjects = getMocksFromGenerator(yourGenerator, 5)
11+
* // [ { name: 'John', age: 23 }, etc... ]
1112
* ```
1213
*/
13-
export const getMocksFromGenerator: TMock = (gen) => (num = 1) => {
14+
export const getMocksFromGenerator: TMock = gen => (num = 1) => {
15+
if (num < 0 || !Number.isInteger(num)) {
16+
throw new Error('Number of mocks must be a non-negative integer')
17+
}
18+
1419
const genRandomObj = () =>
1520
Object.entries(gen).reduce((obj, [prop, callback]) => {
16-
obj[prop] = callback()
21+
try {
22+
obj[prop] = callback()
23+
} catch (error: any) {
24+
let message = `Failed to generate value for property "${prop}": ${error.message}`
25+
console.error(message)
26+
throw new Error(message)
27+
}
1728
return obj
1829
}, Object.create(null))
1930

20-
return Array.from({ length: num }, genRandomObj)
31+
return new Array(num).fill(null).map(() => genRandomObj())
2132
}

utils/get-mocks-with.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ type GetMocksCallableFn = <T extends GenKeys>(p: T[]) => (n: number) => Array<{
3333
* ```ts
3434
* const props = ['name', 'age', 'email']
3535
* const createRandomUsers = generateMocksFrom(props)
36-
* console.log( createRandomUsers(3) ) // [{name:string, age:number, email: string}, ...]
36+
* console.log( createRandomUsers(3) )
37+
* // [ {name:string, age:number, email: string}, etc...]
3738
* ```
3839
*/
3940
export const getMocksWith: GetMocksCallableFn = (properties) => getMocksFromGenerator(getGenerator(properties))

0 commit comments

Comments
 (0)