Skip to content

Commit

Permalink
Merge pull request #1 from asadhshujau/v2
Browse files Browse the repository at this point in the history
refactored to support sample data with the same factory function
  • Loading branch information
asadhshujau authored Sep 26, 2024
2 parents 3b29d4b + d61d582 commit 78cbaf8
Show file tree
Hide file tree
Showing 6 changed files with 198 additions and 153 deletions.
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,17 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [2.0.0] - 2024-09-24

### Changed
- Refactored `factory` function to use an options object for additional parameters.
- Added `isSample` option to explicitly indicate when input should be treated as a sample.
- Consolidated `factory` and `factoryFromSample` into a single `factory` function.
- Maintained backwards compatibility with previous API by supporting a number as the second argument for quantity.

### Deprecated
- `factoryFromSample` function. Use `factory` with `isSample: true` instead.

## [1.4.1] - 2024-09-23

### Added
Expand Down
241 changes: 95 additions & 146 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
# shujau-mock-factory

![CI](https://github.com/asadhshujau/mock-factory/workflows/CI/badge.svg)
[![npm version](https://badge.fury.io/js/shujau-mock-factory.svg)](https://badge.fury.io/js/shujau-mock-factory)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

# shujau-mock-factory
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.

## Features

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

## Installation

Expand All @@ -16,59 +29,60 @@ Using yarn:
yarn add shujau-mock-factory
```

## Usage

Basic usage:
## Quick Start

```javascript
import factory from 'shujau-mock-factory';

// Generate fake data
const users = factory({
id: 'uniqueInt',
name: 'fullName',
email: 'email',
age: { type: 'number', options: { min: 18, max: 65 } }
}, 2);
}, { quantity: 2 });

console.log(users);
```

Advanced usage:
```javascript
import { factory, typeGenerators, resetUniqueIntCounter, setUniqueIntStart } from 'shujau-mock-factory';
## Usage Tips

// start uniqueInt count from 10
setUniqueIntStart(10)
### Obtaining a Single Object

// Use factory as before
const users = factory({ ... }, 2);
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:

// Reset unique integer counter
resetUniqueIntCounter();
```javascript
// Using array destructuring
const [user] = factory({ name: 'fullName', email: 'email' });

// Access type generators directly
const randomName = typeGenerators.fullName();
// Or using array indexing
const user = factory({ name: 'fullName', email: 'email' })[0];
```

## Features
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.

## API Reference

### factory(schemaOrSample, options)

Generates mock data based on the provided schema or sample.

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

## Schema Definition
Returns an array of generated objects.

### Simple Array
### Defining Schemas

#### Simple Array
```javascript
const schema = ['id', 'name', 'email'];
```

### Object with Types
#### Object with Types
```javascript
const schema = {
id: 'uuid',
Expand All @@ -77,7 +91,7 @@ const schema = {
};
```

### Complex Object
#### Complex Object
```javascript
const schema = {
id: 'uniqueInt',
Expand All @@ -95,175 +109,110 @@ const schema = {
};
```

### Custom Generators
```javascript
const schema = {
id: 'uuid',
name: 'fullName',
customField: () => 'Custom Value'
};
```

## API

### factory(schema, quantity = 1)

- `schema`: Object or Array defining the structure of the data to generate
- `quantity`: Number of objects to generate (default: 1)

Returns an array of generated objects based on the schema.

## Supported Types
### Supported Types

- Basic: string, number, boolean
- Basic: string, number, boolean, uuid
- Person: firstName, lastName, fullName, gender, age
- Contact: email, phone
- Contact: email, phone, mobile
- Internet: username, password, url, avatar
- Address: address, street, city, state, country, zipCode, latitude, longitude
- Company: company, companySuffix, jobTitle
- Finance: creditCard, creditCardCVV, iban, bic, bitcoinAddress
- Content: paragraph, sentence, word
- Date/Time: past, future, recent, month, weekday
- Identifiers: uuid
- Content: paragraph, sentence, word, description
- Date/Time: date, datetime, past, future, recent, month, weekday
- Identifiers: uniqueInt
- Miscellaneous: color

## Seeding
### Advanced Usage

You can now set a seed to generate consistent data across multiple runs:
#### Seeding for Consistent Data

You can set a seed to generate consistent data across multiple runs. This can be done in two ways:

1. Using the `setSeed` function:

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

// Set a seed
setSeed(123);
const users = factory({ name: 'fullName', email: 'email' }, { quantity: 2 });
```

// Generate data
const users = factory({
id: 'uniqueInt',
name: 'fullName',
email: 'email'
}, 2);
2. Using the `seed` option in the `factory` function (recommended):

// This will generate the same data every time with the same seed
console.log(users);
```javascript
import { factory } from 'shujau-mock-factory';

const users = factory(
{ name: 'fullName', email: 'email' },
{ quantity: 2, seed: 123 }
);

// This will generate the same data as the previous example
```

## Custom Type Definitions
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.

You can now define your own custom types using the `defineType` function:
#### Custom Type Definitions

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

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

// Use the custom type in a schema
const users = factory({
id: 'uniqueInt',
email: 'customEmail',
name: 'fullName'
}, 2);

console.log(users);
email: 'customEmail'
}, { quantity: 2 });
```

This allows you to create types specific to your use case or domain, enhancing the flexibility of the mock factory.

## Schema Inference

You can now generate mock data based on a sample of your actual data structure using the `factoryFromSample` function:
#### Schema Inference from Sample Data

```javascript
import { factoryFromSample } from 'shujau-mock-factory';
import { factory } from 'shujau-mock-factory';

const sampleData = {
const sampleUser = {
id: 1,
name: "John Doe",
email: "[email protected]",
age: 30,
isActive: true,
tags: ["user", "customer"],
address: {
street: "123 Main St",
city: "Anytown",
zipCode: "12345"
}
age: 30
};

const mockData = factoryFromSample(sampleData, 3);
console.log(mockData);
const users = factory(sampleUser, { quantity: 3, isSample: true });
```

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.

Example with dates:
#### Unique Integer Management

```javascript
import { factoryFromSample } from 'shujau-mock-factory';
import { factory, setUniqueIntStart, resetUniqueIntCounter } from 'shujau-mock-factory';

const sampleData = {
id: 1,
name: "John Doe",
birthDate: "1990-01-01",
createdAt: "2023-01-01T12:00:00Z",
lastLogin: new Date()
};
setUniqueIntStart(1000);
const users = factory({ id: 'uniqueInt', name: 'fullName' }, { quantity: 2 });

const mockData = factoryFromSample(sampleData, 3);
console.log(mockData);
resetUniqueIntCounter(); // Resets the counter to 0
```

## Testing

This package uses Jest for testing. To run the tests:
## Migrating from v1.x to v2.0

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

```bash
npm install
```

or

```bash
yarn
```

#### Run tests:

```bash
npm test
```
```javascript
// Old way (still supported)
const oldWay = factory(schema, 2);

or
// New way
const newWay = factory(schema, { quantity: 2 });

```bash
yarn test
// Using sample data (previously factoryFromSample)
const fromSample = factory(sampleData, { quantity: 2, isSample: true });
```

#### To run tests in watch mode:

```bash
npm run test:watch
```
**or**
```bash
yarn test:watch
```
The `factoryFromSample` function is deprecated and will be removed in the next major version.

The test suite covers various aspects of the shujau-mock-factory, including:
- Simple array schemas
- Object schemas with explicit types
- Nested objects
- Array generation
- Custom generator functions
- Multiple object generation
- Custom type definitions
- Schema Inference
## Contributing

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

## License

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

0 comments on commit 78cbaf8

Please sign in to comment.