Skip to content

Instantly share code, notes, and snippets.

@KennedyIhe
Created April 27, 2020 22:39
Show Gist options
  • Save KennedyIhe/ba06b8e91955186227bd530b9fd90b3f to your computer and use it in GitHub Desktop.
Save KennedyIhe/ba06b8e91955186227bd530b9fd90b3f to your computer and use it in GitHub Desktop.
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