@cloudbase/app
Version:
cloudbase javascript sdk core
62 lines (52 loc) • 1.91 kB
text/typescript
import { langEvent } from '@cloudbase/utilities'
export enum LANGS {
ZH = 'zh-CN',
EN = 'en-US',
}
export const LANG_HEADER_KEY = 'Accept-Language'
export const langMap = {
[LANGS.EN]: {
'请检查调用方式,或前往云开发 AI+ 首页查看文档':
'Please check the calling method or visit the AI+ homepage to view the documentation',
'AI+ 请求出错,错误码': 'AI+ request error, error code',
错误信息: 'error message',
未实现: 'not implemented',
'小程序不支持 wasm 加载': 'wasm loading is not supported in mini programs',
'小程序不支持动态 js 加载': 'dynamic js loading is not supported in mini programs',
请求超时: 'request timeout',
'缺少 privatelink sdk 地址': 'missing privatelink sdk address',
},
}
export const t = (text: string, lang: LANGS) => langMap[lang]?.[text] || text
const getLangCacheKey = config => `lang_${config.clientId || config.env}`
export const i18nProxy = (platform, config) => {
const cacheKey = getLangCacheKey(config)
const { localStorage } = platform.adapter || {}
const lang = config.lang || localStorage?.getItem?.(cacheKey) || LANGS.ZH
localStorage?.setItem?.(cacheKey, lang)
return new Proxy(
{
t: (text: string) => t(text, lang),
LANG_HEADER_KEY,
lang,
},
{
get(target, prop) {
if (prop === 'lang') {
return localStorage?.getItem?.(cacheKey) || target[prop]
}
return target[prop]
},
set(target, prop, newValue) {
if (prop === 'lang' && newValue !== target[prop]) {
target[prop] = newValue
target.t = (text: string) => t(text, newValue)
localStorage?.setItem?.(cacheKey, newValue)
langEvent.bus.fire(langEvent.LANG_CHANGE_EVENT, { i18n: target })
}
target[prop] = newValue
return true
},
},
)
}