@flitz/accept-language
v1.0.0
Published
Extracts information from Accept-Language header field and makes them available in request object of a flitz request.
Downloads
4
Maintainers
Readme
@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: