Files
CoreID/app/assets/app/service/Translate.service.js
garrettmills f06ff83dce
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
Move all front-end public field definitions into constructors for iOS support
2020-10-28 19:53:07 -05:00

60 lines
1.7 KiB
JavaScript

class TranslateService {
constructor() {
this._cache = {}
}
check_cache(...keys) {
const obj = {}
for ( const key of keys ) {
if ( this._cache[key] )
obj[key] = this._cache[key]
else return false
}
return obj
}
async resolve(key) {
const cache_hit = this.check_cache(key)
if ( cache_hit ) return cache_hit[key]
const result = await axios.get('/api/v1/locale/resolve/'+key)
if ( result && result.data && result.data.data ) {
this._cache[key] = result.data.data
return result.data.data
}
}
async load_module(key) {
const result = await axios.get('/api/v1/locale/module/'+key)
if ( result && result.data && result.data.data ) {
for ( const key in result.data.data ) {
if ( !this._cache[key] ) this._cache[key] = result.data.data[key]
}
return result.data.data
}
}
async batch_resolve(...keys) {
const cache_hit = this.check_cache(...keys)
if ( cache_hit ) return cache_hit
const result = await axios.post('/api/v1/locale/batch', { resolvers: keys })
if ( result && result.data && result.data.data ) {
for ( const key in result.data.data ) {
if ( !this._cache[key] ) this._cache[key] = result.data.data[key]
}
return result.data.data
}
}
}
const translate_service = new TranslateService()
const T = (...keys) => {
if ( keys.length === 1 ) return translate_service.resolve(keys[0])
else return translate_service.batch_resolve(...keys)
}
window.T = T
export { translate_service, T }