Skip to content

Instantly share code, notes, and snippets.

@lornajane
Created November 17, 2017 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lornajane/67ca9e53fa72300edbdfe42808251d50 to your computer and use it in GitHub Desktop.
Save lornajane/67ca9e53fa72300edbdfe42808251d50 to your computer and use it in GitHub Desktop.
// fetch document or return null
function getDoc(db, id) {
return new Promise(function(resolve, reject) {
db.get(id).then(resolve).catch(function(err) {
resolve(null);
});
});
};
function main(message) {
var cloudant = require('cloudant')({url: message.cloudantURL, plugin:'promises'});
var db = cloudant.db.use(message.dbname);
var id = message.question.question_id.toString();
// see if there is pre-existing Cloudant document
return getDoc(db, id).then(function(data) {
// if there was no pre-existing document
if (data === null) {
// create new question object
message.question.tags = message.question.tags.sort();
var obj = {
_id: id,
type: 'question',
owner: null,
status: 'new',
question: message.question
};
// write it to the database
return db.insert(obj).then(function(data) {
// pass on the new object to the next action
console.log("Question " + id + " created");
return obj;
});
} else {
// update the existing document
// don't bother updating questions we have already saved
if (message.question.last_activity_date <= data.question.last_activity_date) {
throw new Error('no action required - same data received.');
}
// if we're here we need to update the question - sort the tags first
message.question.tags = message.question.tags.sort();
data.question = message.question;
data.status = 'updated';
// and write it back
return db.insert(data).then(function(reply) {
return data;
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment