import * as fs from 'fs' ; import * as path from 'path' ; import { formatString } from './utils' ; const localeCodeRegex = /^([a-z]{2})-([A-Z]{2})$/ ; export type LocaleType = 'en-US' | 'ja-JP' | 'fr-FR' ; type formatterFunction = ( args ? : object ) => string ; class Translation { param value { string } param resource { string } param namespace { string } private static translate ( value , resource , namespace ) { return resource ? Translation . getResource ( resource , namespace ) [ value ] || value : value ; } private static getResource = ( resource , namespace ) : JSON => ( namespace ? resource [ namespace ] : resource ) ; public loadedResources : object = { } ; private locale : LocaleType = 'en-US' ; param locale public setLocale ( locale ) { if ( ! this . isValidLocale ( locale ) ) { return ; } this . locale = locale ; if ( ! this . loadedResources [ this . locale ] ) { this . loadResource ( this . locale ) ; } } return public getLocale ( ) { return this . locale ; } param locale { LocaleType } public isValidLocale ( locale ) { if ( ! locale ) { return false ; } const localeMatch = locale . match ( localeCodeRegex ) ; return ! ( ! locale && ( ! localeMatch || localeMatch . length < 1 ) ) ; } param value { string } param namespace { string } example returns public t ( value , namespace ? ) { return ( args ? ) : string => { if ( this . loadedResources && this . loadedResources [ this . locale ] ) { return formatString ( Translation . translate ( value , this . loadedResources [ this . locale ] , namespace ) , args ) ; } const resource = this . loadResource ( this . locale ) ; return formatString ( Translation . translate ( value , resource , namespace ) || value , args ) ; } ; } param locale private loadResource ( locale ) { const resourcePath = path . resolve ( __dirname , '..' , 'locale' , `${ locale }.json` ) ; if ( ! fs . existsSync ( resourcePath ) ) { return null ; } return ( this . loadedResources [ this . locale ] = require ( resourcePath ) ) ; } } const i18n = new Translation ( ) ; export { i18n } ;