Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Node.js app that creates a Cosmos DB stored procedure and executes it.
exports.connection = {
endpoint: 'https://localhost:8081',
authKey: 'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=='
};
exports.names = {
database: 'DELETE_ME_SOON',
collection: 'Playground',
};
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