zod-v4-mocks
Version:
Mock generator for zod v4
88 lines (87 loc) • 2.98 kB
JavaScript
import { Faker } from '@faker-js/faker';
import { z } from 'zod/v4';
import { generateMocks } from './generate-from-schema';
import { createMockConfig, getLocales } from './util';
class MockGenerator {
constructor(config) {
const mergedConfig = createMockConfig(config);
const { locale, randomizer, seed, consistentKey } = mergedConfig;
this.options = {
faker: new Faker({ locale: getLocales(locale), randomizer, seed }),
config: mergedConfig,
registry: consistentKey
? z.registry()
: null,
valueStore: new Map(),
arrayIndexes: [],
pinnedHierarchy: new Map(),
};
}
/**
* @description if return value is undefined, fallback to default generator
*/
supply(constructor, value) {
const prevGenerator = this.options.customGenerator;
this.options.customGenerator = (schema, options) => {
if (prevGenerator) {
const res = prevGenerator(schema, options);
if (res !== undefined)
return res;
}
if (schema.constructor.name === constructor.name)
return value;
};
return this;
}
/**
* @description if return value is undefined, fallback to default generator
*/
override(customGenerator) {
const prevGenerator = this.options.customGenerator;
this.options.customGenerator = (schema, options) => {
if (prevGenerator) {
const res = prevGenerator(schema, options);
if (res !== undefined)
return res;
}
return customGenerator(schema, options);
};
return this;
}
register(schemas) {
const { config, registry, valueStore } = this.options;
const length = config.array?.max ?? 10;
for (const schema of schemas) {
const meta = schema.meta();
if (!meta || !config.consistentKey)
continue;
const consistentName = meta[config.consistentKey];
if (!consistentName)
continue;
if (typeof consistentName === 'string') {
registry?.add(schema, { consistentName });
const values = Array.from({ length }, () => generateMocks(schema, this.options));
valueStore?.set(consistentName, values);
}
}
return this;
}
generate(schema) {
return generateMocks(schema, this.options);
}
}
export function initGenerator(config) {
const mockGenerator = new MockGenerator(config);
return mockGenerator;
}
/**
* @deprecated Use generateMock function instead
*/
export class ZodMockGenerator {
constructor(config) {
this.config = createMockConfig(config);
}
generate(schema) {
return initGenerator(this.config).generate(schema);
}
}