@flitz/accept-language
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

npm supported flitz version last build PRs Welcome

@flitz/accept-language

Extracts data from Accept-Language request header field and makes it available in a flitz request.

Install

Run

npm install --save @flitz/accept-language

from the folder, where your package.json is stored.

Usage

const flitz = require('flitz');
const acceptLang = require('@flitz/accept-language');

const run = async () => {
  const app = flitz();

  //        👇👇👇
  app.use(acceptLang('de', 'en'));

  app.get('/', async (req, res) => {
    res.write('Language information: ' + JSON.stringify([
      req.lang,  // selected language, based on submitted languages
      req.languages  // array of submitted languages
    ]));
    res.end();
  });

  await app.listen(3000);
};

run();

Or the TypeScript way:

import flitz from 'flitz';
import { acceptLang } from '@flitz/accept-language';

const run = async () => {
  const app = flitz();

  //        👇👇👇
  app.use(acceptLang('de', 'en'));

  app.get('/', async (req, res) => {
    res.write('Language information: ' + JSON.stringify([
      req.lang,  // selected language, based on submitted languages
      req.languages  // array of submitted languages
    ]));
    res.end();
  });

  await app.listen(3000);
};

run();

Translations

import flitz from 'flitz';
import i18next, { TFunction } from 'i18next';
import { acceptLang } from '@flitz/accept-language';

const run = async () => {
  const app = flitz();

  app.use(acceptLang(
    // set t() function (s. below)
    await initI18(),
    'de', 'en'
  ));

  app.get('/', async (req, res) => {
    res.write('String: ' + req.t!('test'));  // use t() function in req
    res.end();
  });

  await app.listen(3000);
};

const initI18 = () => {
  return new Promise<TFunction>((resolve, reject) => {
    i18next.init({
      fallbackLng: 'de',
      supportedLngs: ['de', 'en'],
      resources: {
        de: {
          translation: {
            test: 'Ein Test'
          }
        },
        en: {
          translation: {
            test: 'A test'
          }
        }
      }
    }, (err, t) => {
      if (err) {
        reject(err);
      } else {
        resolve(t);
      }
    });
  });
};

Credits

The module makes use of:

Package Sidebar

Install

npm i @flitz/accept-language

Weekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

14.5 kB

Total Files

9

Last publish

Collaborators

  • mkloubertego
  • mkloubert