Skip to content

Best practices for using globalize and Node.js with express #460

Open
@dpolivy

Description

@dpolivy

The documentation isn't super clear on this, so I was hoping to get a little clarification/confirmation on the recommended best practices for scenarios using globalize within a node.js app powered by express.

Consider the scenario where an app supports multiple locales, and needs to assign the correct one to each incoming request based on the user's chosen preference. For efficiency, it seems like the best approach is to simply create one Globalize object for each supported locale, and then attach that locale-specific instance to the req object for the request, so it's available for use throughout the various codepaths handling the request. I'm trying to avoid the overhead of having to load data for each new request, utilizing too much memory loading duplicate data (e.g., in multiple instances) and to minimize the amount of work that needs to be done when a request comes in.

Is the right way to do this something like the following?

var Globalize = require('globalize');

// Load the correct i18n content
Globalize.load(
    require('cldr/main/en/currencies.json'),
    require('cldr/main/en/ca-gregorian.json'),
    require('cldr/main/en/dateFields.json'),
    require('cldr/main/en/numbers.json'),
    require('cldr/main/en/timeZoneNames.json'),

    require('cldr/main/fr/currencies.json'),
    require('cldr/main/fr/ca-gregorian.json'),
    require('cldr/main/fr/dateFields.json'),
    require('cldr/main/fr/numbers.json'),
    require('cldr/main/fr/timeZoneNames.json'),

    // Repeat above blocks for each locale we want to support
    // ...

    require('cldr/supplemental/currencyData.json'),
    require('cldr/supplemental/likelySubtags.json'),
    require('cldr/supplemental/numberingSystems.json'),
    require('cldr/supplemental/ordinals.json'),
    require('cldr/supplemental/plurals.json'),
    require('cldr/supplemental/timeData.json'),
    require('cldr/supplemental/weekData.json')
);

var en = new Globalize("en");
var fr = new Globalize("fr");
// ... repeat for each locale we want to support

Or, is it better/possible to create the Globalize objects for each locale, and then load the locale-specific CLDR files into just that instance?

Is it necessary to call Globalize.locale() in this scenario to set a global default locale, or is that only required if one is using the global object, vs individual instances?

All of the examples I've seen only seem to show loading a single locale at a time, so perhaps expanding the docs to discuss this scenario would be helpful for others as well.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions