A i18next language detecting plugin for Koa 2.0 framework.
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src add sessoin detector. May 4, 2017
.babelrc update build script. May 2, 2017
.editorconfig init commit. May 2, 2017
.eslintrc update package.json config. May 2, 2017
.gitignore init commit. May 2, 2017
CHANGELOG.md init commit. May 2, 2017
LICENSE Initial commit May 2, 2017
README.md fix readme error. May 5, 2017
package.json 0.7.1 May 5, 2017

README.md

koa-i18next-detector

NPM Version Coverage Status Build Status Downloads Dependency Status License

A i18next language detecting plugin for Koa 2.0 framework.

Install

npm i -S koa-i18next-detector

Usage

const i18next = require('i18next');
import koaI18nextDetector from "koa-i18next-detector";

// add custom detector.
lngDetector.addDetector({
    name: 'mySessionDetector',

    lookup(ctx, options) {
        let found;
        if (options.lookupSession && ctx && ctx.sessions) {
            found = ctx.sessions[options.lookupMySession];
        }
        return found;
    },

    cacheUserLanguage(ctx, lng, options = {}) {
        if (options.lookupMySession && ctx && ctx.session) {
            ctx.session[options.lookupMySession] = lng;
        }
    }
});

i18next.use(koaI18nextDetector).init({
    fallbackLng: 'en',
    preload: ['en', 'es'],
    resources: {
        en: {
            translation: {
                "key": "hello world"
            }
        },
        es: {
            translation: {
                "key": "es hello world es"
            }
        }
    },
    detection: {
        order: ['querystring', 'path', /*'cookie', 'header',*/ 'session', 'mySessionDetector'],

        lookupQuerystring: 'lng',

        lookupParam: 'lng', // for route like: 'path1/:lng/result'
        lookupFromPathIndex: 0,

        // currently using ctx.cookies
        lookupCookie: 'i18next',
        // cookieExpirationDate: new Date(), // default: +1 year
        // cookieDomain: '', // default: current domain.

        // currently using ctx.session
        lookupSession: 'lng',

        // other options
        lookupMySession: 'lang',

        // cache user language
        caches: ['cookie', 'mySessionDetector']
    }
}, (err, t) => {
    // initialized and ready to go!
    const hw = i18next.t('key'); // hw = 'hello world'
    console.log(hw);
});

License

MIT © lxzxl