Skip to content

Commit 78cbaf8

Browse files
authored
Merge pull request #1 from asadhshujau/v2
refactored to support sample data with the same factory function
2 parents 3b29d4b + d61d582 commit 78cbaf8

File tree

6 files changed

+198
-153
lines changed

6 files changed

+198
-153
lines changed

CHANGELOG.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,17 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [2.0.0] - 2024-09-24
9+
10+
### Changed
11+
- Refactored `factory` function to use an options object for additional parameters.
12+
- Added `isSample` option to explicitly indicate when input should be treated as a sample.
13+
- Consolidated `factory` and `factoryFromSample` into a single `factory` function.
14+
- Maintained backwards compatibility with previous API by supporting a number as the second argument for quantity.
15+
16+
### Deprecated
17+
- `factoryFromSample` function. Use `factory` with `isSample: true` instead.
18+
819
## [1.4.1] - 2024-09-23
920

1021
### Added

README.md

Lines changed: 95 additions & 146 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
1+
# shujau-mock-factory
2+
13
![CI](https://github.com/asadhshujau/mock-factory/workflows/CI/badge.svg)
4+
[![npm version](https://badge.fury.io/js/shujau-mock-factory.svg)](https://badge.fury.io/js/shujau-mock-factory)
5+
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
26

3-
# shujau-mock-factory
7+
A flexible and powerful mock data generator built on top of Faker.js, designed to streamline the creation of realistic test data for your JavaScript applications.
8+
9+
## Features
410

5-
A flexible and powerful fake data generator built on top of Faker.js.
11+
- 🔧 Flexible schema definition
12+
- 🏗 Support for nested objects and arrays
13+
- 🎭 Custom generator functions
14+
- 🌈 Wide range of built-in data types
15+
- 🔢 Consistent data generation with seeding
16+
- 🧩 Custom type definitions
17+
- 🔍 Automatic schema inference from sample data
18+
- ⚙️ Backwards compatibility with previous API
619

720
## Installation
821

@@ -16,59 +29,60 @@ Using yarn:
1629
yarn add shujau-mock-factory
1730
```
1831

19-
## Usage
20-
21-
Basic usage:
32+
## Quick Start
2233

2334
```javascript
2435
import factory from 'shujau-mock-factory';
2536

26-
// Generate fake data
2737
const users = factory({
2838
id: 'uniqueInt',
2939
name: 'fullName',
3040
email: 'email',
3141
age: { type: 'number', options: { min: 18, max: 65 } }
32-
}, 2);
42+
}, { quantity: 2 });
3343

3444
console.log(users);
3545
```
3646

37-
Advanced usage:
38-
```javascript
39-
import { factory, typeGenerators, resetUniqueIntCounter, setUniqueIntStart } from 'shujau-mock-factory';
47+
## Usage Tips
4048

41-
// start uniqueInt count from 10
42-
setUniqueIntStart(10)
49+
### Obtaining a Single Object
4350

44-
// Use factory as before
45-
const users = factory({ ... }, 2);
51+
The `factory` function always returns an array, even when generating a single item. If you need a single object, you can easily extract it using array destructuring or indexing:
4652

47-
// Reset unique integer counter
48-
resetUniqueIntCounter();
53+
```javascript
54+
// Using array destructuring
55+
const [user] = factory({ name: 'fullName', email: 'email' });
4956

50-
// Access type generators directly
51-
const randomName = typeGenerators.fullName();
57+
// Or using array indexing
58+
const user = factory({ name: 'fullName', email: 'email' })[0];
5259
```
5360

54-
## Features
61+
This design ensures consistency and flexibility in the API, allowing you to always work with the result in the same way, regardless of the quantity generated.
62+
63+
## API Reference
64+
65+
### factory(schemaOrSample, options)
66+
67+
Generates mock data based on the provided schema or sample.
5568

56-
- Flexible schema definition
57-
- Supports nested objects and arrays
58-
- Custom generator functions
59-
- Built on Faker.js for a wide range of data types
60-
- Set a seed to generate consistent data across multiple runs
61-
- Custom type definitions
62-
- Schema inference
69+
- `schemaOrSample`: Object or Array defining the structure of the data to generate, or a sample object to infer the schema from.
70+
- `options`: Object (optional)
71+
- `quantity`: Number of objects to generate (default: 1)
72+
- `seed`: Seed for consistent random generation
73+
- `isSample`: Boolean indicating if the first argument is a sample object (default: false)
74+
- `cache`: Object for caching generator functions (advanced usage)
6375

64-
## Schema Definition
76+
Returns an array of generated objects.
6577

66-
### Simple Array
78+
### Defining Schemas
79+
80+
#### Simple Array
6781
```javascript
6882
const schema = ['id', 'name', 'email'];
6983
```
7084

71-
### Object with Types
85+
#### Object with Types
7286
```javascript
7387
const schema = {
7488
id: 'uuid',
@@ -77,7 +91,7 @@ const schema = {
7791
};
7892
```
7993

80-
### Complex Object
94+
#### Complex Object
8195
```javascript
8296
const schema = {
8397
id: 'uniqueInt',
@@ -95,175 +109,110 @@ const schema = {
95109
};
96110
```
97111

98-
### Custom Generators
99-
```javascript
100-
const schema = {
101-
id: 'uuid',
102-
name: 'fullName',
103-
customField: () => 'Custom Value'
104-
};
105-
```
106-
107-
## API
108-
109-
### factory(schema, quantity = 1)
110-
111-
- `schema`: Object or Array defining the structure of the data to generate
112-
- `quantity`: Number of objects to generate (default: 1)
113-
114-
Returns an array of generated objects based on the schema.
115-
116-
## Supported Types
112+
### Supported Types
117113

118-
- Basic: string, number, boolean
114+
- Basic: string, number, boolean, uuid
119115
- Person: firstName, lastName, fullName, gender, age
120-
- Contact: email, phone
116+
- Contact: email, phone, mobile
121117
- Internet: username, password, url, avatar
122118
- Address: address, street, city, state, country, zipCode, latitude, longitude
123119
- Company: company, companySuffix, jobTitle
124120
- Finance: creditCard, creditCardCVV, iban, bic, bitcoinAddress
125-
- Content: paragraph, sentence, word
126-
- Date/Time: past, future, recent, month, weekday
127-
- Identifiers: uuid
121+
- Content: paragraph, sentence, word, description
122+
- Date/Time: date, datetime, past, future, recent, month, weekday
123+
- Identifiers: uniqueInt
128124
- Miscellaneous: color
129125

130-
## Seeding
126+
### Advanced Usage
131127

132-
You can now set a seed to generate consistent data across multiple runs:
128+
#### Seeding for Consistent Data
129+
130+
You can set a seed to generate consistent data across multiple runs. This can be done in two ways:
131+
132+
1. Using the `setSeed` function:
133133

134134
```javascript
135135
import { factory, setSeed } from 'shujau-mock-factory';
136136

137-
// Set a seed
138137
setSeed(123);
138+
const users = factory({ name: 'fullName', email: 'email' }, { quantity: 2 });
139+
```
139140

140-
// Generate data
141-
const users = factory({
142-
id: 'uniqueInt',
143-
name: 'fullName',
144-
email: 'email'
145-
}, 2);
141+
2. Using the `seed` option in the `factory` function (recommended):
146142

147-
// This will generate the same data every time with the same seed
148-
console.log(users);
143+
```javascript
144+
import { factory } from 'shujau-mock-factory';
145+
146+
const users = factory(
147+
{ name: 'fullName', email: 'email' },
148+
{ quantity: 2, seed: 123 }
149+
);
150+
151+
// This will generate the same data as the previous example
149152
```
150153

151-
## Custom Type Definitions
154+
Using the `seed` option is recommended as it allows for more localized control over seeding, especially when you need different seeds for different factory calls in the same script.
152155

153-
You can now define your own custom types using the `defineType` function:
156+
#### Custom Type Definitions
154157

155158
```javascript
156159
import { factory, defineType } from 'shujau-mock-factory';
157160

158-
// Define a custom type
159161
defineType('customEmail', () => `user_${Math.random().toString(36).substr(2, 5)}@example.com`);
160162

161-
// Use the custom type in a schema
162163
const users = factory({
163164
id: 'uniqueInt',
164-
email: 'customEmail',
165-
name: 'fullName'
166-
}, 2);
167-
168-
console.log(users);
165+
email: 'customEmail'
166+
}, { quantity: 2 });
169167
```
170168

171-
This allows you to create types specific to your use case or domain, enhancing the flexibility of the mock factory.
172-
173-
## Schema Inference
174-
175-
You can now generate mock data based on a sample of your actual data structure using the `factoryFromSample` function:
169+
#### Schema Inference from Sample Data
176170

177171
```javascript
178-
import { factoryFromSample } from 'shujau-mock-factory';
172+
import { factory } from 'shujau-mock-factory';
179173

180-
const sampleData = {
174+
const sampleUser = {
181175
id: 1,
182176
name: "John Doe",
183177
184-
age: 30,
185-
isActive: true,
186-
tags: ["user", "customer"],
187-
address: {
188-
street: "123 Main St",
189-
city: "Anytown",
190-
zipCode: "12345"
191-
}
178+
age: 30
192179
};
193180

194-
const mockData = factoryFromSample(sampleData, 3);
195-
console.log(mockData);
181+
const users = factory(sampleUser, { quantity: 3, isSample: true });
196182
```
197183

198-
The `factoryFromSample` function will infer the schema from the sample data and generate appropriate mock data. It supports nested object structures, allowing you to create complex mock data easily.
199-
200-
Example with dates:
184+
#### Unique Integer Management
201185

202186
```javascript
203-
import { factoryFromSample } from 'shujau-mock-factory';
187+
import { factory, setUniqueIntStart, resetUniqueIntCounter } from 'shujau-mock-factory';
204188

205-
const sampleData = {
206-
id: 1,
207-
name: "John Doe",
208-
birthDate: "1990-01-01",
209-
createdAt: "2023-01-01T12:00:00Z",
210-
lastLogin: new Date()
211-
};
189+
setUniqueIntStart(1000);
190+
const users = factory({ id: 'uniqueInt', name: 'fullName' }, { quantity: 2 });
212191

213-
const mockData = factoryFromSample(sampleData, 3);
214-
console.log(mockData);
192+
resetUniqueIntCounter(); // Resets the counter to 0
215193
```
216194

217-
## Testing
218-
219-
This package uses Jest for testing. To run the tests:
195+
## Migrating from v1.x to v2.0
220196

221-
#### Install dependencies:
197+
Version 2.0 introduces a new options object for the `factory` function, but maintains backwards compatibility:
222198

223-
```bash
224-
npm install
225-
```
226-
227-
or
228-
229-
```bash
230-
yarn
231-
```
232-
233-
#### Run tests:
234-
235-
```bash
236-
npm test
237-
```
199+
```javascript
200+
// Old way (still supported)
201+
const oldWay = factory(schema, 2);
238202

239-
or
203+
// New way
204+
const newWay = factory(schema, { quantity: 2 });
240205

241-
```bash
242-
yarn test
206+
// Using sample data (previously factoryFromSample)
207+
const fromSample = factory(sampleData, { quantity: 2, isSample: true });
243208
```
244209

245-
#### To run tests in watch mode:
246-
247-
```bash
248-
npm run test:watch
249-
```
250-
**or**
251-
```bash
252-
yarn test:watch
253-
```
210+
The `factoryFromSample` function is deprecated and will be removed in the next major version.
254211

255-
The test suite covers various aspects of the shujau-mock-factory, including:
256-
- Simple array schemas
257-
- Object schemas with explicit types
258-
- Nested objects
259-
- Array generation
260-
- Custom generator functions
261-
- Multiple object generation
262-
- Custom type definitions
263-
- Schema Inference
212+
## Contributing
264213

265-
If you're contributing to this project, please ensure that your changes are covered by tests.
214+
Contributions are welcome! Please feel free to submit a Pull Request.
266215

267216
## License
268217

269-
MIT
218+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

0 commit comments

Comments
 (0)