Skip to content

Instantly share code, notes, and snippets.

@KennedyIhe

KennedyIhe/translate.js Secret

Created Apr 27, 2020
Embed
What would you like to do?
const mkdirp = require('mkdirp');
const config = require('../configs/translations-config')
const CosmosClient = require('@azure/cosmos').CosmosClient
const fs = require('fs');
const endpoint = config.endpoint;
const key = config.key;
const databaseId = config.database.id;
const containerId = config.container.id;
const client = new CosmosClient({ endpoint, key });
async function initDatabase() {
createDatabase()
.then(() => readDatabase())
.then(() => createContainer())
.then(() => readContainer())
.then(() => createLanguageItem(config.items.en))
.then(() => createLanguageItem(config.items.es))
.then(() => createTranslationFiles())
.then(() => {
exit(`Completed successfully`)
})
.catch(error => {
exit(`Completed with error ${JSON.stringify(error)}`)
})
}
function exit(message) {
process.stdin.setRawMode(true)
process.stdin.resume()
process.stdin.on('data', process.exit.bind(process, 0))
}
async function createDatabase() {
const { database } = await client.databases.createIfNotExists({
id: databaseId
})
}
async function readDatabase() {
const { resource: databaseDefinition } = await client.database(databaseId).read()
}
async function createContainer() {
const { container } = await client.database(databaseId)
.containers.createIfNotExists(
{ id: containerId },
{ offerThroughput: 400 }
)
}
async function readContainer() {
const { resource: containerDefinition } = await client.database(databaseId).container(containerId).read()
}
async function createLanguageItem(itemBody) {
const { item } = await client.database(databaseId).container(containerId).items.upsert(itemBody)
}
async function createTranslationFiles() {
console.log(`Querying container:\n${config.container.id}`);
const supportedLanguages = ['en', 'es'];
const LANG_DIR = './src/translations/';
const querySpec = { query: 'SELECT * FROM docs' }
const { resources: results } = await client.database(databaseId).container(containerId).items.query(querySpec).fetchAll();
const dir = mkdirp.sync(LANG_DIR);
for (var doc of results) {
fs.writeFileSync(`${LANG_DIR + doc.code}.json`, JSON.stringify(doc, null, 2));
}
}
initDatabase();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment