import * as _ from 'lodash' ; import * as xmlParser from 'xml2js' ; import { Injectable } from '@nestjs/common' ; import { CitizenStatus } from '../dto' ; import { Genders , RnippResponseCodes , RnippXmlSelectors } from '../enums' ; import { RnippHttpStatusException } from '../exceptions' ; const FRANCE_COG = '99100' ; @ Injectable ( ) export class RnippResponseParserService { public async parseRnippData ( xmlData ) { const options = { tagNameProcessors : [ xmlParser . processors . stripPrefix ] , } ; let json ; try { json = await xmlParser . parseStringPromise ( xmlData , options ) ; } catch ( error ) { throw new RnippHttpStatusException ( ) ; } return this . extractXmlAttributes ( json ) ; } private extractXmlAttributes ( parsedXml ) { const rnippCode = this . getXmlAttribute ( parsedXml , RnippXmlSelectors . RNIPP_CODE ) ; if ( rnippCode !== RnippResponseCodes . FOUND_NOT_RECTIFIED && rnippCode !== RnippResponseCodes . FOUND_RECTIFIED ) { return { rnippCode } ; } const deceased = this . getDeceasedStateAttribute ( parsedXml , RnippXmlSelectors . DECEASED ) ; const identity = { gender : this . getGenderFromParsedXml ( parsedXml , RnippXmlSelectors . GENDER ) , family_name : this . getXmlAttribute ( parsedXml , RnippXmlSelectors . FAMILY_NAME ) , given_name : this . getGivenNamesAttribute ( parsedXml , RnippXmlSelectors . GIVEN_NAME ) , birthdate : this . getXmlAttribute ( parsedXml , RnippXmlSelectors . BIRTH_DATE ) , birthplace : this . getXmlAttribute ( parsedXml , RnippXmlSelectors . BIRTH_PLACE ) , birthcountry : this . getBirthcountryAttribute ( parsedXml , RnippXmlSelectors . BIRTH_PLACE , RnippXmlSelectors . BIRTH_COUNTRY ) , } ; return { identity , deceased , rnippCode , } ; } private getXmlAttribute ( parsedXml , path , defaultValue = '' ) { return _ . get ( parsedXml , path , defaultValue ) ; } private getGenderFromParsedXml ( parsedXml , path ) { const rnippGender = this . getXmlAttribute ( parsedXml , path ) ; switch ( rnippGender ) { case 'F' : return Genders . FEMALE ; case 'M' : return Genders . MALE ; case 'U' : return Genders . UNSPECIFIED ; default : return '' ; } } private getGivenNamesAttribute ( parsedXml , path ) { const givenNames = this . getXmlAttribute ( parsedXml , path , [ ] ) ; return givenNames . join ( ' ' ) ; } private getDeceasedStateAttribute ( parsedXml , path ) { return ! ! this . getXmlAttribute ( parsedXml , path , false ) ; } private getBirthcountryAttribute ( parsedXml , birthplacePath , birthcountryPath ) { const birthplace = this . getXmlAttribute ( parsedXml , birthplacePath ) ; const birthcountry = this . getXmlAttribute ( parsedXml , birthcountryPath ) ; if ( ! birthplace && ! birthcountry ) { return '' ; } return birthcountry || FRANCE_COG ; } }