schema-mocker
schema-mocker
Schema-based fake data for TypeScript & JavaScript — generate from schemas, Zod/Yup, or sample API responses.
Works with React, Vue, Angular, and vanilla JS/TS
Features
- Schema-based generation with rich field types (
givenName,currencyincl. ETB,price, …) - Smart mock — pass a schema, Zod/Yup schema, or a sample JSON response
- API simulation — pagination,
meta,links(default|laravel|rails|cursor|json:api) - Relational datasets (
belongsTo,hasOne,hasMany,manyToMany) - Seeds, weighted/
oneOf, computed & conditional fields, nested objects & arrays - Optional Zod / Yup adapters
- Lightweight publish layout (minified Rollup bundles +
.d.tsonly)
Install
npm install schema-mocker
Optional peers:
npm install zod # Zod adapter
npm install yup # Yup adapter
Quick start
import { generate, generateMany, FIELD_TYPES } from 'schema-mocker';
const user = generate({
id: 'uuid',
givenName: FIELD_TYPES.givenName,
familyName: 'familyName',
email: 'email',
age: { type: 'age', min: 18, max: 65 },
currency: 'currency', // often includes ETB
city: 'city'
});
const users = generateMany({ name: 'fullName', email: 'email' }, 10);
Smart mock (schema or response)
import { mock, mockMany, mockFromResponse, fromResponse } from 'schema-mocker';
// From sample API payload → infer schema → generate
const sample = {
id: '550e8400-e29b-41d4-a716-446655440000',
given_name: 'Abebe',
email: 'abebe@example.com',
currency: 'ETB',
amount: 250.5
};
fromResponse(sample); // inferred schema
mock(sample); // one object
mockMany(sample, 20); // twenty objects
mockFromResponse(sample, 20);
// Also accepts Zod / Yup schemas
// mock(zodSchema); mockMany(yupSchema, 10);
Simulate paginated APIs
import { simulateApi, simulateApiAsync, simulateApiError } from 'schema-mocker';
const res = simulateApi(
{ id: 'uuid', name: 'product', price: 'price', currency: 'currency' },
{
pagination: { page: 1, pageSize: 10, total: 57 },
resource: 'products',
path: '/api/products',
style: 'default' // 'laravel' | 'rails' | 'cursor' | 'json:api'
}
);
// { success, status, data, meta: { page, pageSize, total, ... }, links }
await simulateApiAsync(schema, { delayMs: 300, pagination: { page: 2, pageSize: 5 } });
simulateApiError({ status: 422, message: 'Validation failed', errors: [{ field: 'email', message: 'required' }] });
Relational data
import { generateRelational, generateOneToMany } from 'schema-mocker';
const db = generateRelational({
entities: {
users: { schema: { id: 'uuid', name: 'fullName' }, count: 5 },
posts: { schema: { id: 'uuid', title: 'sentence' }, count: 20 }
},
relations: [
{ from: 'posts', to: 'users', type: 'belongsTo', foreignKey: 'userId' },
{ from: 'users', to: 'posts', type: 'hasMany', as: 'posts', foreignKey: 'userId' }
]
});
const { parents, children } = generateOneToMany({
parent: { id: 'uuid', name: 'fullName' },
child: { id: 'uuid', title: 'sentence' },
parentCount: 3,
childrenPerParent: [1, 4],
foreignKey: 'userId',
as: 'posts'
});
Zod / Yup
import { z } from 'zod';
import { fromZodSchema, generate, generateFromZod } from 'schema-mocker';
const zodSchema = z.object({
name: z.string(),
age: z.number().min(18).max(100),
email: z.string().email()
});
generate(fromZodSchema(zodSchema));
// or
generateFromZod(zodSchema);
Field types
Use string shortcuts or FIELD_TYPES.*.
| Group | Types |
|---|---|
| Names | name, givenName / firstName, middleName, familyName / lastName, fullName, userName / username, password |
| Contact | email, phone |
| Location | address / street, city, state, country, countryCode, zipCode / postalCode, latitude, longitude, timezone, locale |
| Time | date, datetime, timestamp, birthday, age |
| Numbers / money | number / integer, float, price, currency (incl. ETB), currencySymbol, percentage, boolean |
| IDs / tech | id, uuid, slug, url, domain, ip / ipv4, ipv6, mac, hex, base64, fileName, mimeType, status, gender |
| Content | text, lorem / word, sentence, paragraph, html, markdown, color, image / avatar, product, sku |
| Business | company, jobTitle, department, creditCard, ssn, isbn, custom |
import { FIELD_TYPES, resolveFieldType, getFieldTypesByGroup } from 'schema-mocker';
resolveFieldType('given_name'); // 'givenName'
getFieldTypesByGroup('names');
Schema syntax
// shortcut
{ name: 'fullName', email: 'email' }
// options
{ age: { type: 'number', min: 18, max: 65 } }
// nested + arrays of objects
{
address: { city: 'city', country: 'country' },
tags: { type: 'text', array: true, arrayLength: [2, 5] },
comments: {
type: 'custom',
array: true,
arrayLength: [1, 3],
items: { id: 'uuid', body: 'sentence' }
}
}
ID options
{
id: {
type: 'id',
idOptions: { type: 'uuid' | 'number' | 'incremental', min, max, start, step, prefix, suffix }
}
}
Framework entry points
// React
import { useFaker, generate } from 'schema-mocker/react';
// Vue
import { useFaker, generate } from 'schema-mocker/vue';
// Angular
import { FakerService, generate } from 'schema-mocker/angular';
Prefer importing core APIs from schema-mocker and only using /react, /vue, or /angular for the thin helpers (useFaker / FakerService).
Seeds
import { generate, SchemaFaker } from 'schema-mocker';
generate({ name: 'fullName' }, { seed: 12345 });
const faker = new SchemaFaker({ seed: 12345 });
faker.generate({ email: 'email' });
Main exports
| API | Purpose |
|---|---|
generate / generateMany |
Core generation |
mock / mockMany / mockFromResponse |
Schema or Zod/Yup or sample response |
fromResponse / inferSchemaFromSample |
Response → schema |
simulateApi / simulateApiAsync / wrapApiResponse / simulateApiError |
API envelopes + pagination |
generateRelational / generateOneToMany / withRelations |
Relations |
fromZodSchema / generateFromZod |
Zod |
fromYupSchema / generateFromYup |
Yup |
FIELD_TYPES / resolveFieldType |
Typed field helpers |
CURRENCIES / CURRENCY_SYMBOLS |
Currency lists (incl. ETB / Br) |
SchemaFaker |
Class API |
See CHANGELOG.md for version history.
License
MIT © Hanibal Girmay
Related Packages
@framit/meta-pixel
Simple, framework agnostic and GDPR Compliance library to track data to Meta Pix...
15,362
5
@homedia/meta-pixel
Simple, framework agnostic and GDPR Compliance library to track data to Meta Pix...
1,961
@dlhsoft/ganttcharthyperlibrary
Gantt Chart library for JavaScript and TypeScript with Angular, React, and Vue e...
2,650
2
@nativescript-community/geocoding
Provides access to native geocoding APIs for NativeScript apps (android.location...
2,162
8
Version History
| Version | Released | Vue | License |
|---|---|---|---|
| 1.2.2 | ^2.6.0 || | MIT | |
| 1.1.1 | ^2.6.0 || | MIT | |
| 1.0.1 | ^2.6.0 || | MIT | |
| 1.0.0 | ^2.6.0 || | MIT |