Last active
December 9, 2018 21:09
-
-
Save devjourney/34c7b514f8f86b28b6a079354b80182b to your computer and use it in GitHub Desktop.
A Node.js app that creates a Cosmos DB stored procedure and executes it.
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
exports.connection = { | |
endpoint: 'https://localhost:8081', | |
authKey: 'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==' | |
}; | |
exports.names = { | |
database: 'DELETE_ME_SOON', | |
collection: 'Playground', | |
}; |
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
var CosmosClient = require('@azure/cosmos').CosmosClient; | |
var config = require('./config.js'); | |
var client = new CosmosClient({ | |
endpoint: config.connection.endpoint, | |
auth: { masterKey: config.connection.authKey } | |
}); | |
async function upsertProcedureAndExecute(sprocDef, docToInsert) { | |
const { database } = await client.databases | |
.createIfNotExists({ id: config.names.database }); | |
const { container } = await database.containers | |
.createIfNotExists({ id: config.names.collection }); | |
const { sproc } = await container.storedProcedures.upsert(sprocDef); | |
const { body: results, headers } = await sproc.execute(docToInsert); | |
if (headers && headers['x-ms-request-charge']) | |
console.log(`Charge = ${headers['x-ms-request-charge']} RU`); | |
if (results) | |
console.log(`DocID = ${JSON.stringify(results)}`); | |
// comment in the next line to delete the database | |
// await database.delete(); | |
} | |
var docToSave = { | |
message: 'Hello Cosmos DB', | |
timestamp: (new Date()).toISOString() | |
}; | |
var procedureDef = { | |
id: 'saveDocument', | |
body: function (doc) { | |
var accepted = __.upsertDocument(__.getSelfLink(), | |
doc, | |
function (err, newDoc) { | |
if (err) throw err; | |
__.response.setBody({ id: newDoc.id, completed: true }) | |
}); | |
if (!accepted) __.response.setBody({ completed: false }); | |
} | |
}; | |
upsertProcedureAndExecute(procedureDef, docToSave) | |
.catch((err) => { console.error(JSON.stringify(err)); }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment