Created
March 9, 2023 21:42
-
-
Save aVolpe/82a31d2d53b07e3b9680c03b98e6023a to your computer and use it in GitHub Desktop.
i18next react with traduora
This file contains hidden or 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
export async function setupI18n(config: { | |
traduora: { | |
host: string, | |
projectId: string, | |
clientId: string, | |
clientSecret: string | |
} | |
}) { | |
const token = await getTraduoraToken(config.traduora); | |
return i18n | |
// load translation using xhr -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales) | |
// learn more: https://github.com/i18next/i18next-xhr-backend | |
.use(Backend) | |
// detect user language | |
// learn more: https://github.com/i18next/i18next-browser-languageDetector | |
.use(LanguageDetector) | |
// pass the i18n instance to react-i18next. | |
.use(initReactI18next) | |
// init i18next | |
// for all options read: https://www.i18next.com/overview/configuration-options | |
.init({ | |
fallbackLng: 'en', | |
debug: false, | |
backend: { | |
loadPath: `${config.traduora.host}/api/v1/projects/${config.traduora.projectId}/exports?locale={{lng}}&format=jsonflat`, | |
customHeaders: { | |
"Accept": "application/octet-stream", | |
"Authorization": `Bearer ${token}` | |
} | |
} | |
}); | |
} | |
async function getTraduoraToken(params: { host: string, clientId: string, clientSecret: string }) { | |
const response = await fetch(`${params.host}/api/v1/auth/token`, { | |
method: 'POST', | |
headers: { | |
"Accept": "application/json", | |
"Content-Type": "application/json" | |
}, | |
body: JSON.stringify({ | |
grant_type: 'client_credentials', | |
client_id: params.clientId, | |
client_secret: params.clientSecret}) | |
}); | |
if (response.ok) { | |
const asJson: { access_token: string } = await response.json(); | |
return asJson.access_token; | |
} | |
console.warn(response); | |
throw new Error("Can't get traduora token"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment