UNPKG

documentdb-utils

Version:

Drop-in replacement+extensions for Azure's DocumentDB node.js client with auto-retry on 429 errors plus a lot more

121 lines (112 loc) 3.02 kB
// Generated by CoffeeScript 1.9.2 (function() { var utils; utils = {}; utils.clone = function(obj) { var flags, key, newInstance; if ((obj == null) || typeof obj !== 'object') { return obj; } if (obj instanceof Date) { return new Date(obj.getTime()); } if (obj instanceof RegExp) { flags = ''; if (obj.global != null) { flags += 'g'; } if (obj.ignoreCase != null) { flags += 'i'; } if (obj.multiline != null) { flags += 'm'; } if (obj.sticky != null) { flags += 'y'; } return new RegExp(obj.source, flags); } newInstance = new obj.constructor(); for (key in obj) { newInstance[key] = utils.clone(obj[key]); } return newInstance; }; /** * If it exists, this will fetch the database. If it does not exist, it will create the database. * @param {Client} client * @param {string} databaseID * @param {callback} callback */ module.exports.getOrCreateDatabase = function(client, databaseID, callback) { var querySpec; querySpec = { query: "SELECT * FROM root r WHERE r.id=@id", parameters: [ { name: "@id", value: databaseID } ] }; return client.queryDatabases(querySpec).toArray(function(err, results) { var databaseSpec; if (err) { return callback(err); } else { if (results.length === 0) { databaseSpec = { id: databaseID }; return client.createDatabase(databaseSpec, function(err, created) { if (err) { return callback(err); } else { return callback(null, created); } }); } else { return callback(null, results[0]); } } }); }; module.exports.getOrCreateCollection = function(client, databaseLink, collectionID, callback) { var querySpec; querySpec = { query: "SELECT * FROM root r WHERE r.id=@id", parameters: [ { name: "@id", value: collectionID } ] }; return client.queryCollections(databaseLink, querySpec).toArray(function(err, results) { var collectionSpec, offerType, requestOptions; if (err) { return callback(err); } else { if (results.length === 0) { collectionSpec = { id: collectionID }; offerType = config.offerType || "S1"; requestOptions = { offerType: offerType }; return client.createCollection(databaseLink, collectionSpec, requestOptions, function(err, created) { if (err) { return callback(err); } else { return callback(null, created); } }); } else { return callback(null, results[0]); } } }); }; module.exports = documentDBUtils; }).call(this);