schema-mocker
v1.1.1
Published
A powerful schema-based faker plugin for generating random data in TypeScript and JavaScript
Maintainers
Readme
🎭 schema-mocker
A powerful, schema-based faker plugin for generating random data in TypeScript and JavaScript
Works seamlessly with React, Vue, Angular, and vanilla JS/TS
Quick Start • Documentation • Examples • API Reference
📋 Table of Contents
- ✨ Features
- 🚀 Quick Start
- 📚 Documentation
- 🎯 Examples
- 🛠️ Utilities
- 📖 API Reference
- 🔗 Schema Relationships
- 🌱 Understanding Seeds
- ⭐ Unique Differentiators
- 📄 License
✨ Features
- 🎯 Schema-based generation - Define your data structure and generate matching fake data
- 🔢 Flexible ID generation - Support for numeric IDs, UUIDs, and incremental IDs with customizable options
- 🌱 Seed support - Reproducible random data generation for testing
- 🔗 Relationships & References - Generate related data with foreign key references
- ⚖️ Weighted random selection - Probability-based value selection
- 🧮 Computed fields - Fields that depend on other generated fields
- 🔀 Conditional generation - Generate fields based on conditions (if/else logic)
- 📊 Array generation - Generate arrays with configurable lengths
- 🔄 Transform functions - Post-process generated values
- 📦 Framework agnostic - Works with React, Vue, Angular, and vanilla JS/TS
- 🎨 Rich data types - Generate names, emails, addresses, dates, and much more
- 💪 TypeScript support - Full type safety and IntelliSense
- 🔌 Zod & Yup integration - Use your existing Zod or Yup schemas to generate fake data (optional)
- 🚀 Lightweight - Minimal dependencies (only requires
uuidfor UUID generation)
🚀 Quick Start
Installation
npm install schema-mocker
# or
yarn add schema-mocker
# or
pnpm add schema-mockerOptional dependencies (for Zod/Yup integration):
npm install zod # For Zod schema support
npm install yup # For Yup schema supportBasic Usage
import { generate } from 'schema-mocker';
const user = generate({
id: { type: 'id', idOptions: { type: 'uuid' } },
name: 'fullName',
email: 'email',
age: { type: 'number', min: 18, max: 65 }
});
console.log(user);
// {
// id: '550e8400-e29b-41d4-a716-446655440000',
// name: 'John Smith',
// email: '[email protected]',
// age: 42
// }Generate multiple items:
import { generateMany } from 'schema-mocker';
const users = generateMany({
id: { type: 'id' },
name: 'fullName',
email: 'email'
}, 10);
console.log(users); // Array of 10 user objects📚 Documentation
Schema Types
All field types with autocomplete support in TypeScript:
Text & Names
text- Random text string (5-20 chars by default)name/fullName- Full name (first + last)firstName- First namelastName- Last name
Contact Information
email- Email addressphone- Phone numberaddress- Street addresscity- City namecountry- Country namezipCode- ZIP/postal code
Numbers & Dates
number- Random number (0-100 by default)date- Date string (ISO format: YYYY-MM-DD)boolean- Random boolean (true/false)
IDs & Identifiers
id- ID (number or UUID, see ID Generation)uuid- UUID v4 string
Web & Media
url- URL stringimage- Image URL (Picsum Photos)
Content
product- Product name (e.g., "Wireless Headphones Pro")lorem/word- Random lorem ipsum wordsentence- Random sentence (5-15 words)paragraph- Random paragraph (3-7 sentences)
Business
color- Hex color code (#RRGGBB)company- Company namejobTitle- Job title
Custom
custom- Custom type with your own generator
💡 TypeScript Autocomplete: When you type a field value as a string, you'll get autocomplete suggestions for all field types!
Schema Syntax
You can define schemas in three ways:
1. Shortcut Syntax (String) - Recommended
const schema = {
name: 'fullName',
email: 'email',
age: 'number'
};2. Object Syntax (Full Control)
const schema = {
name: { type: 'fullName' },
email: { type: 'email' },
age: { type: 'number', min: 18, max: 65 },
bio: { type: 'paragraph' }
};3. Nested Schemas
const schema = {
id: { type: 'id', idOptions: { type: 'uuid' } },
name: 'fullName',
address: {
street: 'address',
city: 'city',
country: 'country',
zipCode: 'zipCode'
}
};ID Generation
The id type supports flexible ID generation with options:
Number ID
const schema = {
id: {
type: 'id',
idOptions: {
type: 'number',
min: 1,
max: 1000,
prefix: 'USER_',
suffix: '_ID'
}
}
};
// Generates: 'USER_123_ID'UUID
const schema = {
id: {
type: 'id',
idOptions: {
type: 'uuid',
prefix: 'id-',
suffix: '-end'
}
}
};
// Generates: 'id-550e8400-e29b-41d4-a716-446655440000-end'Incremental ID
import { SchemaFaker } from 'schema-mocker';
const faker = new SchemaFaker();
const schema = {
id: {
type: 'id',
idOptions: {
type: 'incremental',
start: 1,
step: 1,
prefix: 'USER-'
}
}
};
// Generates: 'USER-1', 'USER-2', 'USER-3', ...Default ID (Number)
const schema = {
id: 'id' // Uses default: number between 1 and 1000000
};🎯 Examples
Basic Examples
Simple User Schema
import { generate } from 'schema-mocker';
const user = generate({
id: { type: 'id', idOptions: { type: 'uuid' } },
name: 'fullName',
email: 'email',
age: { type: 'number', min: 18, max: 65 },
isActive: 'boolean',
createdAt: 'date'
});Product Schema
const product = generate({
name: 'product',
price: { type: 'number', min: 10, max: 1000 },
description: 'paragraph',
tags: { type: 'text', array: true, arrayLength: [3, 5] },
image: 'image',
color: 'color'
});Nested Address Schema
const userWithAddress = generate({
name: 'fullName',
email: 'email',
address: {
street: 'address',
city: 'city',
country: 'country',
zipCode: 'zipCode'
}
});Advanced Features
Custom Generators
const schema = {
customField: {
generator: () => {
return 'My custom value';
}
},
timestamp: {
generator: () => new Date().toISOString()
}
};OneOf (Random Selection)
const schema = {
status: {
oneOf: ['active', 'inactive', 'pending']
},
role: {
oneOf: ['admin', 'user', 'guest']
}
};Weighted OneOf (Probability-based)
const schema = {
status: {
weightedOneOf: [
{ value: 'active', weight: 70 }, // 70% chance
{ value: 'inactive', weight: 20 }, // 20% chance
{ value: 'pending', weight: 10 } // 10% chance
]
}
};Computed Fields
const schema = {
firstName: 'firstName',
lastName: 'lastName',
fullName: {
computed: true,
generator: (ctx) => `${ctx.firstName} ${ctx.lastName}`
},
email: {
computed: true,
generator: (ctx) => `${ctx.firstName.toLowerCase()}.${ctx.lastName.toLowerCase()}@example.com`
}
};Conditional Generation
const schema = {
status: { oneOf: ['active', 'inactive'] },
discount: {
conditional: {
field: 'status',
operator: '==',
value: 'active',
then: { type: 'number', min: 5, max: 25 }
}
}
};Array Generation
const schema = {
tags: { type: 'text', array: true, arrayLength: 5 },
items: { type: 'text', array: true, arrayLength: [3, 10] },
numbers: { type: 'number', array: true, arrayLength: [2, 5], min: 1, max: 100 }
};Transform Functions
const schema = {
name: {
type: 'fullName',
transform: (value) => value.toUpperCase()
},
slug: {
computed: true,
generator: (ctx) => ctx.name.toLowerCase().replace(/\s+/g, '-'),
transform: (value) => value.replace(/[^a-z0-9-]/g, '')
}
};Custom Type
const schema = {
customField: {
type: 'custom',
customType: {
name: 'myCustomType',
preview: 'Example Value', // Shown in IDE/documentation
generator: (context) => {
return `Custom-${Math.random().toString(36).substring(7)}`;
}
}
}
};Framework Integration
React
import { generate, generateMany } from 'schema-mocker/react';
import { useFaker } from 'schema-mocker/react';
// Direct usage
function UserList() {
const users = generateMany({
id: { type: 'id', idOptions: { type: 'uuid' } },
name: 'fullName',
email: 'email',
avatar: 'image'
}, 5);
return (
<div>
{users.map(user => (
<div key={user.id}>
<img src={user.avatar} alt={user.name} />
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
))}
</div>
);
}
// With hook
function UserProfile() {
const user = useFaker({
name: 'fullName',
email: 'email',
age: { type: 'number', min: 18, max: 65 }
});
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
<p>Age: {user.age}</p>
</div>
);
}Vue 2/3
<template>
<div>
<div v-for="user in users" :key="user.id">
<h3>{{ user.name }}</h3>
<p>{{ user.email }}</p>
</div>
</div>
</template>
<script setup>
import { generateMany } from 'schema-mocker/vue';
import { useFaker } from 'schema-mocker/vue';
// Direct usage
const users = generateMany({
id: { type: 'id', idOptions: { type: 'uuid' } },
name: 'fullName',
email: 'email'
}, 5);
// With composable
const user = useFaker({
name: 'fullName',
email: 'email',
age: { type: 'number', min: 18, max: 65 }
});
</script>Angular
import { Component } from '@angular/core';
import { FakerService } from 'schema-mocker/angular';
@Component({
selector: 'app-user-list',
template: `
<div *ngFor="let user of users">
<h3>{{ user.name }}</h3>
<p>{{ user.email }}</p>
</div>
`
})
export class UserListComponent {
users: any[];
constructor(private faker: FakerService) {
this.users = this.faker.generateMany({
id: { type: 'id', idOptions: { type: 'uuid' } },
name: 'fullName',
email: 'email'
}, 5);
}
}Zod & Yup Integration
Using Zod Schemas
import { z } from 'zod';
import { fromZodSchema, generate, generateFromZod } from 'schema-mocker';
// Define your Zod schema (same as you use for validation)
const userSchema = z.object({
name: z.string(),
age: z.number().min(18).max(100),
email: z.string().email(),
isActive: z.boolean(),
tags: z.array(z.string()).min(1).max(5)
});
// Option 1: Convert then generate
const schema = fromZodSchema(userSchema);
const user = generate(schema);
// Option 2: Generate directly from Zod schema
const user2 = generateFromZod(userSchema);Supported Zod Features:
- ✅
z.string()→text(with min/max length) - ✅
z.string().email()→email - ✅
z.string().url()→url - ✅
z.string().uuid()→uuid - ✅
z.number()→number(with min/max) - ✅
z.boolean()→boolean - ✅
z.date()→date - ✅
z.array()→ arrays with length constraints - ✅
z.enum()→oneOfselection - ✅
z.object()→ nested objects - ✅
z.optional()→ optional fields - ✅
z.nullable()→ nullable fields
Using Yup Schemas
import * as yup from 'yup';
import { fromYupSchema, generate, generateFromYup } from 'schema-mocker';
// Define your Yup schema (same as you use for validation)
const productSchema = yup.object({
name: yup.string().min(5).max(50).required(),
price: yup.number().min(0).max(1000).required(),
description: yup.string().min(10).max(200),
tags: yup.array().of(yup.string()).min(1).max(5),
category: yup.string().oneOf(['electronics', 'clothing', 'food', 'books']).required()
});
// Option 1: Convert then generate
const schema = fromYupSchema(productSchema);
const product = generate(schema);
// Option 2: Generate directly from Yup schema
const product2 = generateFromYup(productSchema);Supported Yup Features:
- ✅
yup.string()→text(with min/max length) - ✅
yup.string().email()→email - ✅
yup.string().url()→url - ✅
yup.string().uuid()→uuid - ✅
yup.number()→number(with min/max) - ✅
yup.boolean()→boolean - ✅
yup.date()→date - ✅
yup.array()→ arrays with length constraints - ✅
yup.string().oneOf()→oneOfselection - ✅
yup.object()→ nested objects
🛠️ Utilities
Utility Functions
generateId(options?: IdOptions): string | number
Generates an ID based on options. Can be used directly for custom ID generation.
import { generateId } from 'schema-mocker';
// Number ID
const id1 = generateId({ type: 'number', min: 1, max: 1000 });
console.log(id1); // e.g., 542
// UUID
const id2 = generateId({ type: 'uuid', prefix: 'USER-' });
console.log(id2); // e.g., "USER-550e8400-e29b-41d4-a716-446655440000"
// Custom prefix/suffix
const id3 = generateId({
type: 'number',
prefix: 'PROD-',
suffix: '-END',
min: 100,
max: 999
});
console.log(id3); // e.g., "PROD-456-END"generateField(field: SchemaField, context?: any): any
Low-level function to generate a single field value. Usually called internally, but can be used for custom field generation.
import { generateField } from 'schema-mocker';
// Simple field
const name = generateField({ type: 'fullName' });
console.log(name); // e.g., "John Smith"
// Field with options
const email = generateField({ type: 'email' });
console.log(email); // e.g., "[email protected]"
// Field with constraints
const age = generateField({ type: 'number', min: 18, max: 65 });
console.log(age); // e.g., 42
// With context (for computed fields)
const computed = generateField(
{
computed: true,
generator: (ctx) => `${ctx.firstName} ${ctx.lastName}`
},
{ firstName: 'John', lastName: 'Doe' }
);
console.log(computed); // "John Doe"SeededRandom Class
A seeded random number generator class for reproducible randomness.
import { SeededRandom } from 'schema-mocker';
// Create with seed
const random = new SeededRandom(12345);
// Generate random numbers (deterministic with same seed)
const num = random.random(); // 0.123456789 (same every time with seed 12345)
const int = random.randomInt(1, 100); // e.g., 42 (same every time)
const float = random.randomFloat(0, 1); // e.g., 0.789 (same every time)
// Pick random element
const element = random.randomElement(['a', 'b', 'c', 'd']); // e.g., 'b'
// Shuffle array
const shuffled = random.shuffle([1, 2, 3, 4, 5]); // e.g., [3, 1, 5, 2, 4]
// Change seed
random.setSeed(99999);
const newNum = random.random(); // Different value now
// Get current seed
console.log(random.getSeed()); // 99999Methods:
random()- Generate random number between 0 and 1randomInt(min, max)- Generate random integer (inclusive)randomFloat(min, max)- Generate random floatrandomElement<T>(array)- Pick random element from arrayshuffle<T>(array)- Shuffle array using seeded randomsetSeed(seed)- Set seed valuegetSeed()- Get current seed value
getSeededRandom(seed?: number): SeededRandom
Gets or creates a global seeded random number generator instance.
import { getSeededRandom } from 'schema-mocker';
// Get or create global instance with seed
const random1 = getSeededRandom(12345);
console.log(random1.random()); // e.g., 0.123456789
// Get same instance (seed already set)
const random2 = getSeededRandom();
console.log(random2.random()); // Next number in sequence
// Change seed
const random3 = getSeededRandom(99999);
console.log(random3.random()); // Different sequence nowresetSeededRandom(): void
Resets the global seeded random instance. Useful for testing.
import { resetSeededRandom } from 'schema-mocker';
resetSeededRandom(); // Clear global instance
console.log('Global random instance has been reset');FIELD_TYPES Enum
Enum-like object of all available field types. Use dot notation to access types.
import { FIELD_TYPES, generate } from 'schema-mocker';
// Use like an enum with dot notation
const schema = {
name: FIELD_TYPES.fullName, // ✅ Type-safe, autocomplete available
email: FIELD_TYPES.email, // ✅ FIELD_TYPES.email
age: FIELD_TYPES.number, // ✅ FIELD_TYPES.number
isActive: FIELD_TYPES.boolean // ✅ FIELD_TYPES.boolean
};
// Or use string shortcuts (also has autocomplete!)
const schema2 = {
name: 'fullName', // ✅ TypeScript autocomplete shows all types
email: 'email' // ✅ Autocomplete available
};Available properties (all 27 field types):
FIELD_TYPES.text- Random text stringFIELD_TYPES.name- Full name (alias for fullName)FIELD_TYPES.firstName- First nameFIELD_TYPES.lastName- Last nameFIELD_TYPES.fullName- Full name (first + last)FIELD_TYPES.email- Email addressFIELD_TYPES.phone- Phone numberFIELD_TYPES.address- Street addressFIELD_TYPES.city- City nameFIELD_TYPES.country- Country nameFIELD_TYPES.zipCode- ZIP/postal codeFIELD_TYPES.date- Date string (ISO format)FIELD_TYPES.number- Random numberFIELD_TYPES.boolean- Random booleanFIELD_TYPES.id- ID (number or UUID)FIELD_TYPES.uuid- UUID v4 stringFIELD_TYPES.url- URL stringFIELD_TYPES.image- Image URLFIELD_TYPES.product- Product nameFIELD_TYPES.lorem- Random lorem wordFIELD_TYPES.word- Random word (alias for lorem)FIELD_TYPES.sentence- Random sentenceFIELD_TYPES.paragraph- Random paragraphFIELD_TYPES.color- Hex color codeFIELD_TYPES.company- Company nameFIELD_TYPES.jobTitle- Job titleFIELD_TYPES.custom- Custom type
📖 API Reference
Core Functions
generate<T>(schema: T, options?: FakerOptions): GeneratedData<T>
Generates a single object based on the schema.
Parameters:
schema- Schema definition objectoptions- Optional faker configuration (seed, entities, etc.)
Returns: Generated data matching the schema structure
Example:
import { generate } from 'schema-mocker';
const user = generate({
name: 'fullName',
email: 'email',
age: { type: 'number', min: 18, max: 65 }
});generateMany<T>(schema: T, count: number, options?: FakerOptions): GeneratedData<T>[]
Generates an array of objects based on the schema.
Parameters:
schema- Schema definition objectcount- Number of items to generateoptions- Optional faker configuration
Returns: Array of generated data objects
Example:
import { generateMany } from 'schema-mocker';
const users = generateMany({
name: 'fullName',
email: 'email'
}, 10);SchemaFaker Class
Constructor
new SchemaFaker(options?: FakerOptions)Options:
seed?: number- Seed for reproducible randomnessidCounters?: { [key: string]: number }- Initial ID countersschemaRegistry?: { [schemaName: string]: Schema }- Pre-registered schemas
Example:
import { SchemaFaker } from 'schema-mocker';
const faker = new SchemaFaker({
seed: 12345,
idCounters: { user: 0, product: 0 }
});Methods
generate<T>(schema: T): GeneratedData<T>
Generates a single object based on the schema.
generateMany<T>(schema: T, count: number): GeneratedData<T>[]
Generates multiple objects based on the schema.
setSeed(seed: number): void
Sets the seed for reproducible random data generation.
getSeed(): number | undefined
Gets the current seed value.
resetCounters(): void
Resets all ID counters.
registerSchema(name: string, schema: Schema): void
Registers a schema for use in relationships.
defineRelationship(from: string, to: string, type: 'oneToOne' | 'oneToMany' | 'manyToMany'): void
Defines a relationship between schemas.
Zod & Yup Adapters
fromZodSchema(zodSchema: any): Schema
Converts a Zod schema to schema-mocker's internal schema format.
Example:
import { z } from 'zod';
import { fromZodSchema, generate } from 'schema-mocker';
const zodSchema = z.object({
name: z.string(),
age: z.number().min(18).max(100),
email: z.string().email()
});
const schema = fromZodSchema(zodSchema);
const user = generate(schema);generateFromZod(zodSchema: any, options?: FakerOptions): any
Generates fake data directly from a Zod schema without converting first.
fromYupSchema(yupSchema: any): Schema
Converts a Yup schema to schema-mocker's internal schema format.
generateFromYup(yupSchema: any, options?: FakerOptions): any
Generates fake data directly from a Yup schema without converting first.
Type Definitions
All types are exported for use in your code:
import type {
Schema,
SchemaField,
SchemaFieldType,
SchemaWithRelations,
GeneratedData,
FakerOptions,
IdOptions,
WeightedOption,
ConditionalRule,
SchemaRelationship
} from 'schema-mocker';🔗 Schema Relationships
Schema-mocker supports schema-level relationships for generating related data:
One-to-One Relationship
import { SchemaFaker } from 'schema-mocker';
const faker = new SchemaFaker();
// Register schemas
faker.registerSchema('user', {
id: { type: 'id' },
name: 'fullName'
});
faker.registerSchema('profile', {
userId: { type: 'id' },
bio: 'paragraph'
});
// Define relationship
faker.defineRelationship('user', 'profile', 'oneToOne');
// Generate with relationships
const userWithProfile = faker.generateWithRelations('user');
// Automatically generates related profileOne-to-Many Relationship
faker.defineRelationship('user', 'order', 'oneToMany');
const userWithOrders = faker.generateWithRelations('user');
// Automatically generates related orders arrayMany-to-Many Relationship
faker.defineRelationship('user', 'tag', 'manyToMany');
const userWithTags = faker.generateWithRelations('user');
// Automatically generates related tags array🌱 Understanding Seeds
Seeds allow you to generate the same random data every time, which is perfect for:
- Testing: Consistent test data
- Debugging: Reproduce the exact same data to debug issues
- Documentation: Show the same examples every time
- Snapshots: Create reproducible data snapshots
How to Use Seeds
import { SchemaFaker } from 'schema-mocker';
// Create faker with seed
const faker = new SchemaFaker({ seed: 12345 });
// Generate data - will be the same every time
const user1 = faker.generate({
name: 'fullName',
age: { type: 'number', min: 18, max: 65 }
});
// user1.name = "John Smith" (always the same with seed 12345)
// user1.age = 42 (always the same with seed 12345)
// Reset to same seed
faker.setSeed(12345);
const user2 = faker.generate({
name: 'fullName',
age: { type: 'number', min: 18, max: 65 }
});
// user2.name === user1.name (same!)
// user2.age === user1.age (same!)
// Different seed = different results
faker.setSeed(99999);
const user3 = faker.generate({
name: 'fullName',
age: { type: 'number', min: 18, max: 65 }
});
// user3.name !== user1.name (different!)Seed Best Practices
- ✅ Use seeds in tests for consistent results
- ✅ Use seeds in development to debug specific data scenarios
- ✅ Use meaningful seed numbers (like
12345,42) for documentation examples - ❌ Don't use seeds in production if you need truly random data
⭐ Unique Differentiators
This faker plugin stands out from others with these unique features:
- 🌱 Seed Support - Reproducible data generation for consistent testing
- 🔗 Schema Relationships - Built-in support for one-to-one, one-to-many, and many-to-many relationships with automatic generation
- 🔗 Field References - Reference existing entities in your data generation
- ⚖️ Weighted Selection - Probability-based value selection (not just random)
- 🧮 Computed Fields - Fields that automatically compute based on other generated fields
- 🔀 Conditional Logic - If/else generation based on field values
- 📊 Smart Arrays - Generate arrays with configurable lengths and nested structures
- 🔄 Transform Pipeline - Post-process values with transform functions
- 🔢 Incremental IDs - Sequential ID generation for realistic data patterns
- 📦 Framework Integration - First-class support for React, Vue, and Angular
- 💪 TypeScript First - Full type safety and IntelliSense support
- 🔌 Zod/Yup Integration - Use existing validation schemas for data generation
📄 License
MIT
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Made with ❤️ by Hanibal Girmay
⭐ Star on GitHub • 📖 Documentation • 🐛 Report Bug • 💡 Request Feature
