@italia-tools/faker
Version:
Italian-specific fake data generator based on Faker.js
71 lines (68 loc) • 3.04 kB
JavaScript
import { FiscalCodeGenerator } from '../utils/fiscalCode.mjs';
import { Gender } from '../types/types.mjs';
import { PlacesModule } from './places.module.mjs';
import { FirstNameModule } from './firstName.module.mjs';
import { LastNameModule } from './lastName.module.mjs';
import { of, forkJoin, lastValueFrom } from 'rxjs';
import { map } from 'rxjs/operators';
class FiscalCodeModule {
constructor(faker) {
this.faker = faker;
this.placesModule = new PlacesModule(faker);
this.firstNameModule = new FirstNameModule(faker);
this.lastNameModule = new LastNameModule(faker);
}
generate$(options) {
const gender = options?.gender ?? this.faker.helpers.arrayElement([Gender.Male, Gender.Female]);
const birthDate = options?.birthDate ?? this.faker.date.birthdate();
const firstName$ = options?.firstName
? of(options.firstName)
: this.firstNameModule.firstName$();
const lastName$ = options?.lastName
? of(options.lastName)
: this.lastNameModule.lastName$();
const birthPlace$ = options?.birthPlace
? this.validateBirthPlace(options.birthPlace)
: this.placesModule.randomCity$().pipe(map(city => ({ type: 'italian', city })));
return forkJoin({
firstName: firstName$,
lastName: lastName$,
birthPlace: birthPlace$
}).pipe(map(({ firstName, lastName, birthPlace }) => FiscalCodeGenerator.generate({
firstName,
lastName,
gender,
birthDate,
birthPlace
})));
}
async generate(options) {
return lastValueFrom(this.generate$(options));
}
validateBirthPlace(birthPlace) {
if (birthPlace.type === 'italian' && birthPlace.city && birthPlace.city.belfioreCode) {
return this.placesModule.city$({ belfioreCode: birthPlace.city.belfioreCode }).pipe(map(city => {
if (!city)
throw new Error('Invalid Belfiore Code');
return { type: 'italian', city };
}));
}
if (birthPlace.type === 'italian' && birthPlace.city && birthPlace.city.name) {
return this.placesModule.city$({ cityName: birthPlace.city.name }).pipe(map(city => {
if (!city)
throw new Error('Invalid city name');
return { type: 'italian', city };
}));
}
if (birthPlace.type === 'foreign' && birthPlace.country?.name) {
return this.placesModule.getCountryByName$(birthPlace.country.name).pipe(map(country => {
if (!country)
throw new Error(`Invalid country name: ${birthPlace.country.name}`);
const countryDto = { name: country.nameEn, code: country.atCode };
return { type: 'foreign', country: countryDto };
}));
}
throw new Error('Invalid birth place');
}
}
export { FiscalCodeModule };