-
Notifications
You must be signed in to change notification settings - Fork 107
/
app.js
90 lines (77 loc) · 2.71 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*jshint node:true */
"use strict";
var DocumentDBClient = require('documentdb').DocumentClient;
var DocumentDBUtils = require('../utils');
var config = require('../config');
// Cache Database and Collection self-links.
var databaseLink, collectionLink, sprocLink;
// Initialize DocumentDB Client.
var docDbClient = new DocumentDBClient(config.connection.endpoint, {
masterKey: config.connection.authKey
});
// Path to stored procedure definition
var sprocDefinition = require('./JS/upsert');
// Execute the stored procedure with the following parameters.
var sprocParams = [{
id: "myDocument",
foo: "bar"
}];
// Get or Create the Database
DocumentDBUtils.getOrCreateDatabase(docDbClient, config.names.database, function(db) {
databaseLink = db._self;
// Get or Create the Collection
DocumentDBUtils.getOrCreateCollection(docDbClient, databaseLink, config.names.collection, function(coll) {
collectionLink = coll._self;
console.log("Upserting the sproc: '" + sprocDefinition.id + "'");
upsertSproc(docDbClient, collectionLink, sprocDefinition, function(err, sproc) {
if (err) throw err;
console.log("Executing the sproc: '" + sproc.id + "'");
console.log('Sproc parameters: ' + JSON.stringify(sprocParams));
executeSproc(docDbClient, sproc._self, sprocParams);
});
});
});
function upsertSproc(client, collectionLink, sprocDefinition, callback) {
var query = {
query: 'SELECT * FROM sprocs s WHERE s.id = @id',
parameters: [{
name: '@id',
value: sprocDefinition.id
}]
};
// Query for the stored procedure.
client.queryStoredProcedures(collectionLink, query, null).toArray(function(err, results) {
if (err) throw err;
if (results.length > 0) {
// Delete it if it exists and re-create it.
client.deleteStoredProcedure(results[0]._self, null, function(err) {
client.createStoredProcedure(collectionLink, sprocDefinition, null, function(err, sproc) {
callback(null, sproc);
});
});
} else {
// Otherwise just create the sproc.
client.createStoredProcedure(collectionLink, sprocDefinition, null, function(err, sproc) {
callback(null, sproc);
});
}
});
}
function executeSproc(client, sprocLink, sprocParams) {
client.executeStoredProcedure(sprocLink, sprocParams, function(err, results, responseHeaders) {
console.log('//////////////////////////////////');
if (err) {
console.log('// err');
console.log(err);
}
if (responseHeaders) {
console.log('// responseHeaders');
console.log(responseHeaders);
}
if (results) {
console.log('// results');
console.log(results);
}
console.log('//////////////////////////////////');
});
}