import { Faker, base, de, en, es, fr, it } from '@faker-js/faker' import dateFormat from 'date-format' import PersonGenerator, { PersonGeneratorOptions } from './PersonGenerator' export type TextGeneratorOptions = { seed?: number locale?: string refDate?: string | Date | number } const DEFAULT_REF_DATE = '2020-01-01T00:00:00.000Z' function formatDate(date: Date, format?: string): string { return format !== undefined ? dateFormat(format, date) : dateFormat(date) } function resolveLocales(locale?: string) { switch (locale) { case 'de': return [de, en, base] case 'es': return [es, en, base] case 'fr': return [fr, en, base] case 'it': return [it, en, base] default: return [en, base] } } export default class TextGenerator { public generator: Faker public seed: number constructor(opts?: TextGeneratorOptions) { this.seed = opts?.seed ?? Date.now() ^ (Math.random() * 0x100000000) this.generator = new Faker({ locale: resolveLocales(opts?.locale), seed: this.seed, }) this.generator.setDefaultRefDate(opts?.refDate ?? DEFAULT_REF_DATE) } public person(opts: PersonGeneratorOptions ): PersonGenerator { return new PersonGenerator(this.generator, opts) } public slug(min: number, max: number): string { return this.generator.lorem.slug({ min, max }) } public sentence(min: number, max: number): string { return this.generator.lorem.sentence({ min, max }) } public paragraph(min: number, max: number): string { return this.generator.lorem.paragraph({ min, max }) } public date( when: 'recent'|'past'|'soon'|'future'|'anytime', format?: string ): string { switch (when) { case 'anytime': { const date = new Date(this.generator.date.anytime().toISOString()) return formatDate(date, format) } case 'recent': { const date = new Date(this.generator.date.recent().toISOString()) return formatDate(date, format) } case 'past': { const date = new Date(this.generator.date.past().toISOString()) return formatDate(date, format) } case 'soon': { const date = new Date(this.generator.date.soon().toISOString()) return formatDate(date, format) } case 'future': { const date = new Date(this.generator.date.future().toISOString()) return formatDate(date, format) } default: { const date = new Date(this.generator.date.anytime().toISOString()) return formatDate(date, format) } } } }