npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

hmpo-countries-lib

v7.1.2

Published

Country lists

Readme

hmpo-countries-lib

Country data API cache and wrapper library

In-depth API Documentation can be found in API_DOCS.md.

The documentation is auto-generated from the JS Docs in index.js using documentation.js.

You can re-generate the documentation after making changes by running:

npm run documentation

This will also run as part of the pre-push hook.

Features and benefits of hmpo-countries-lib

  • API Wrapping: Acts as an intermediary for an external country data source.
  • Caching: Caches country data locally to speed up access and reduce load on the source API. Supports Redis via a store factory.
  • Automatic Polling: Periodically fetches updates from the source API in the background.
  • Flexible Retrieval: Offers methods to get:
    • All countries.
    • Filtered lists (e.g., resident, overseas, birth countries).
    • Specific country data by ID, slug, or display name.
  • Lifecycle Management: Provides start() and stop() methods to control the polling process.

Pre-requisites

hmpo-countries-lib requires a store, such as a redis client factory, in order to interface with the usage of hmpo-cached-model in this library. hmpo-cached-model requires that its store object has a function getClient().

See hmpo-cached-model for more information.

Installation

Add hmpo-countries-lib to your project via npm or yarn

npm install hmpo-countries-lib
yarn add hmpo-countries-lib

Usage

You might create your custom hmpo-countries-lib instance under a file such as lib/custom-country-lib.js.

This file will:

  • Export the configured hmpo-countries-lib class.
  • Define the behaviour of the methods:
    • onFail()
    • onError()
    • on()

Begin polling for country data

const CountriesLib = require('hmpo-countries-lib');

// redisFactory is our store, exposing getClient() which is required by hmpo-cached-model.
let redisFactory = {
    getClient() {
        return redisInstance;
    }
}

let countriesLib = new CountriesLib({
    store: redisFactory,  // This will be passed to a constructor for hmpo-cached-model, or a muted extension of it.
    key: 'store-key-prefix',
    storeInterval: 10000, // 10 seconds - The interval to write a snapshot of the country data to redis
    countryUrl: 'http://example.com/api/countries',
    countryInterval: 3000000 // 5 minutes - The interval to poll the Country API URL for updated country data
});

// start polling
countriesLib.start();

API Documentation

Full documentation for hmpo-countries-lib can be found at API Docs.

A few examples as follows:


// Get an array of all countries
let allCountries = countriesLib.getAllCountries();

// Get arrays of countries from pre-defined catagories
let overseasCountries = countriesLib.getOverseasCountries();

// Get a specific country using a unique identifer
let countryData = countriesLib.getCountryDataById('GB');

// Get information on a specific country
let isUkRestricted = countriesLib.isRestrictedById('UK'); // false

Sorting & formatting for dropdown lists

Once you have a list of countries:

let allCountries = countriesLib.getAllCountries();

You can sort the countries alphabetically. This will put GB at the top if it is included in the list.

let sortedCountries = countriesLib.sortCountryList(allCountries);

You can transform a list of countries into a dropdown-friendly format. This will automatically sort the list.

// Optionally translate country names to welsh using the `isWelsh` flag.
let countriesDropdownList = countriesLib.dropdownList(allCountries, false);

There are also specific dropdownList methods for Birth and Residence Countries. All of these have an optional isWelsh param to translate names to Welsh.

e.g.

// Birth Countries
let birthCountriesDropdown = countriesLib.dropdownListBirthCountries();

Custom failure handling

Logs a custom failure message in the format: 'Countries CachedModel request failed :outVerb :outRequest :outResponseCode :outError'

// Example Usage

fetch('https://api.example.com/countries')
    .then(async (response) => {
        const data = await response.json();
        if (!response.ok) {
            const exampleError = new Error(data.error || 'Request failed');
            exampleError.body = JSON.stringify(data);
            this.onFail(exampleError, data, {
                method: 'GET',
                url: 'https://api.example.com/countries'
            }, response.status, response.headers.get('X-Response-Time') || 0);
        } else {
            // Handle successful response
            console.log('Countries:', data);
        }
    })
    .catch((err) => {
        // Some other error
        this.onFail(err, null, {
            method: 'GET',
            url: 'https://api.example.com/countries'
        }, 0, 0);
    });

Stop polling for country data

// stop polling
countriesLib.stop();