Created
February 12, 2015 03:33
-
-
Save traviskaufman/d403a34dfd2ae1fba77d to your computer and use it in GitHub Desktop.
Minimal i18n plugin for HapiJS using node-i18n
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
import _ from 'lodash'; | |
import i18n from 'i18n'; | |
import {version} from '../../package.json'; | |
registerI18n.attributes = { name: 'i18n', version }; | |
export default registerI18n; | |
const i18nApi = [ '__', '__n', 'setLocale', 'getLocale', 'getCatalog' ].reduce(function(api, methodName) { | |
api[methodName] = function(...args) { | |
return this.raw.req[methodName](...args); | |
}; | |
return api; | |
}, {}); | |
function registerI18n(server, options, next) { | |
i18n.configure(_.defaults({}, options)); | |
server.ext('onPreHandler', function(request, reply) { | |
const { req, res } = request.raw; | |
i18n.init(req, res); | |
_.mixin(request, i18nApi); | |
reply.continue(); | |
}); | |
next(); | |
} | |
// Then in code after registering... | |
server.route({ | |
method: 'GET', | |
path: '/', | |
handler: function(request, reply) { | |
var msg = request.__('Hello! Nice to meet you'); | |
reply(msg); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment