Wrap module function and change its return

Viewed 42

I'm using node-i18n-iso-countries and I want to override getNames function that takes 2 args so it can handle a new country name that I want to add.

Currently, I'm just doing it with an if-else statement this way:

let countryName = country === 'countryName' ? 'countryName' 
: isoCountries.getName(code, lang);

Is there a more optimal way to do this? for example wrapping the isoCountries.getName function?

I'm new to TypeScript and function wrapping. So a reply with a snippet / an existing question might help please!

1 Answers

It's possible to register a locale with registerLocale and override the needed languages with a new country in the list of already defined countries.

Solution 1

Do it like this by importing the JSON directly.

import isoCountries, { LocaleData } from 'i18n-iso-countries'
import enJson from 'i18n-iso-countries/langs/en.json'

const localeData: LocaleData = enJson;
localeData.countries['AA'] = 'Test Country Name'
isoCountries.registerLocale(localeData)
console.log(isoCountries.getName('AA', 'en'))
// ^ Prints: Test Country Name

Solution 2

If it's not possible to import a JSON, rebuild the locale data from scratch like this:

import isoCountries, { LocaleData } from 'i18n-iso-countries'

const localeData: LocaleData = {
  locale: 'en',
  countries: isoCountries.getNames('en', { select: 'all' }),
};
localeData.countries['AA'] = 'Test Country Name'
isoCountries.registerLocale(localeData)
console.log(isoCountries.getName('AA', 'en'))
Related