Created
November 17, 2017 15:42
-
-
Save lornajane/67ca9e53fa72300edbdfe42808251d50 to your computer and use it in GitHub Desktop.
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
// 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