Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@doodle/i18n / dist / express.js
Size: Mime:
const fs = require('fs');
const path = require('path');
const acceptLanguageParser = require('accept-language-parser');
const { Router } = require('express');
const locales = require('./locales');

const DEFAULT_LOCALE = 'en';
const COOKIE_MAX_AGE = 13824000;

let __nodeModulesPath = path.resolve(__dirname, './node_modules');
let __i18nPath = './i18n';

const init = (nodeModulesPath, i18nPath) => {
  __nodeModulesPath = nodeModulesPath || __nodeModulesPath;
  __i18nPath = i18nPath || __i18nPath;
};

const getLocaleFromAcceptedLanguages = req => {
  const acceptedLanguages = acceptLanguageParser.parse(req.headers['accept-language']);
  if (acceptedLanguages && acceptedLanguages.length && acceptedLanguages[0].code) {
    return acceptedLanguages[0].code === '*' ? DEFAULT_LOCALE : acceptedLanguages[0].code;
  }
  return DEFAULT_LOCALE;
};

/**
 * Cookie middleware
 */
const cookie = (req, res, next) => {
  let locale;

  if (req.cookies && req.cookies.locale) {
    locale = req.cookies.locale;
    if (typeof locales[locale] === 'undefined') {
      locale = DEFAULT_LOCALE;
      res.cookie('locale', locale, {
        maxAge: COOKIE_MAX_AGE,
      });
    }
  } else {
    if (req.headers && req.headers['accept-language']) {
      locale = getLocaleFromAcceptedLanguages(req);
    }

    if (!locale || !locales[locale]) {
      locale = DEFAULT_LOCALE;
    }

    res.cookie('locale', locale, {
      maxAge: COOKIE_MAX_AGE,
    });
  }

  req.locale = locale;
  next();
};

/**
 * API middleware
 */
const api = Router();
api.get('/i18n/localeData/:locale', (req, res) => {
  // Follows IETF language tag convention:
  // https://en.wikipedia.org/wiki/IETF_language_tag
  const locale = req.params.locale.split('-')[0];
  res.sendFile(`${__nodeModulesPath}/react-intl/locale-data/${locale}.js`);
});

api.get('/i18n/messages/:locale', (req, res) => {
  const locale = req.params.locale;

  fs.readFile(`${__i18nPath}/${locale}.json`, 'utf-8', (err, data) => {
    if (!err) {
      res[req.query.callback ? 'jsonp' : 'json'](JSON.parse(data));
    } else {
      res.status(404).send('Not found');
    }
  });
});

/**
 * Exports
 */
module.exports = (() => (nodeModulesPath, i18nPath) => {
  init(nodeModulesPath, i18nPath);
  return [cookie, api];
})();