import { plainToInstance } from 'class-transformer' ; import { validateOrReject } from 'class-validator' ; import countries from 'world-countries/dist/countries-unescaped.json' ; import type { Countries , Country } from 'world-countries' ; import { WorldCountry } from './world-country' ; import { WorldCountryQuery } from './world-country-query' ; import type { WorldCountryQueryInterface } from './world-country-query.interface' ; export class WorldCountryUtil { /**
     * Returns the result if at least one of the fields matches
     */ private static match ( country , filters ) { const keys = Object . keys ( filters ) as unknown as Array < keyof WorldCountryQuery > ; for ( const key of keys ) { const searchValue = filters [ key ] ?. toString ( ) . toLowerCase ( ) ; if ( key === 'name' ) { if ( country . name . common . toLowerCase ( ) === searchValue || country . name . official . toLowerCase ( ) === searchValue ) { return true ; } } else if ( country [ key ] ?. toString ( ) . toLowerCase ( ) === searchValue ) { return true ; } } return false ; } static async find ( _query ) { const query = plainToInstance < WorldCountryQuery , WorldCountryQueryInterface > ( WorldCountryQuery , _query ) ; const keys = Object . keys ( query ) as unknown as Array < keyof WorldCountryQueryInterface > ; for ( const key of keys ) { if ( ! query [ key ] ) { delete query [ key ] ; } } try { await validateOrReject ( query , { whitelist : true , forbidNonWhitelisted : true , validationError : { target : false , value : false } , } ) ; } catch ( err ) { return ; } const countryData = ( countries as unknown as Countries ) . find ( ( plainCountry ) => { const country = plainToInstance < WorldCountry , Country > ( WorldCountry , plainCountry ) ; return WorldCountryUtil . match ( country , query ) ; } ) ; if ( ! countryData ) { return ; } return plainToInstance < WorldCountry , Country > ( WorldCountry , countryData ) ; } }