@italia-tools/faker
Version:
Italian-specific fake data generator based on Faker.js
73 lines (69 loc) • 3.18 kB
JavaScript
;
var fiscalCode = require('../utils/fiscalCode.cjs');
var types = require('../types/types.cjs');
var places_module = require('./places.module.cjs');
var firstName_module = require('./firstName.module.cjs');
var lastName_module = require('./lastName.module.cjs');
var rxjs = require('rxjs');
var operators = require('rxjs/operators');
class FiscalCodeModule {
constructor(faker) {
this.faker = faker;
this.placesModule = new places_module.PlacesModule(faker);
this.firstNameModule = new firstName_module.FirstNameModule(faker);
this.lastNameModule = new lastName_module.LastNameModule(faker);
}
generate$(options) {
const gender = options?.gender ?? this.faker.helpers.arrayElement([types.Gender.Male, types.Gender.Female]);
const birthDate = options?.birthDate ?? this.faker.date.birthdate();
const firstName$ = options?.firstName
? rxjs.of(options.firstName)
: this.firstNameModule.firstName$();
const lastName$ = options?.lastName
? rxjs.of(options.lastName)
: this.lastNameModule.lastName$();
const birthPlace$ = options?.birthPlace
? this.validateBirthPlace(options.birthPlace)
: this.placesModule.randomCity$().pipe(operators.map(city => ({ type: 'italian', city })));
return rxjs.forkJoin({
firstName: firstName$,
lastName: lastName$,
birthPlace: birthPlace$
}).pipe(operators.map(({ firstName, lastName, birthPlace }) => fiscalCode.FiscalCodeGenerator.generate({
firstName,
lastName,
gender,
birthDate,
birthPlace
})));
}
async generate(options) {
return rxjs.lastValueFrom(this.generate$(options));
}
validateBirthPlace(birthPlace) {
if (birthPlace.type === 'italian' && birthPlace.city && birthPlace.city.belfioreCode) {
return this.placesModule.city$({ belfioreCode: birthPlace.city.belfioreCode }).pipe(operators.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(operators.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(operators.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');
}
}
exports.FiscalCodeModule = FiscalCodeModule;