blazepress
Version:
A rapid web application development platform for Node.js
80 lines (46 loc) • 1.11 kB
JavaScript
const util = require( 'util' )
class Language {
constructor( path, language ) {
this.path = path
this.language = language || 'en'
this.langs = new Map
this.nspaces = new Map
}
ns( key ) {
let nspace = this.nspaces.get( key )
if( !nspace ) {
nspace = new Language( this.path.sub( key ) )
this.nspaces.set( key, nspace )
}
return nspace
}
get( key, ...args ) {
let path, type, value, lang = this.langs.get( this.language )
if( !lang ) {
path = this.path.sub( this.language )
try {
lang = require( path.str )
} catch( err ) {
throw new Error( 'Language: could not load ' + path + '\nDetails: ' + err )
}
this.langs.set( this.language, lang )
}
value = lang[ key ]
type = typeof value
switch( type ) {
case 'function':
value = value( ...args )
break
case 'string':
value = util.format( value, ...args )
break
default:
throw new TypeError(
'typeof @value for ' + key + ' is ' + type +
' but it should be "function" or "string"'
)
}
return value
}
}
module.exports = Language