From a0b426e7a277346aae32f1362bcfcb22ef5d0839 Mon Sep 17 00:00:00 2001 From: Jan Philipp Timme Date: Wed, 18 Sep 2013 16:00:43 +0200 Subject: [PATCH] [TASK] Create new profile document on DELETE /profile. --- src/Profile.api.js | 68 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 59 insertions(+), 9 deletions(-) diff --git a/src/Profile.api.js b/src/Profile.api.js index 95f955c..fe188e0 100644 --- a/src/Profile.api.js +++ b/src/Profile.api.js @@ -62,21 +62,71 @@ var constructor = function(db) { } if(req.method == "DELETE") { - var changeset = { - "data": {} - }; - db.merge(req.session.data.user.profile, changeset, function(err, result) { + db.get(req.session.data.user.profile, function(err, doc) { if(err) { console.log(err); res.send(200, JSON.stringify({ "success": false, - "error": "Something went wrong updating the profile document!" - })); - } else { - res.send(200, JSON.stringify({ - "success": true + "error": "Could not fetch old profile document!" })); + return; } + //delete profile document + db.remove(doc._id, doc._rev, function(err, result) { + if(err) { + console.log(err); + res.send(200, JSON.stringify({ + "success": false, + "error": "Could not remove old profile document!" + })); + return; + } + //create new profile document + db.save({ + "type": "profile", + "data": {} + }, function(err, result) { + if(err) { + console.log(err); + res.send(200, JSON.stringify({ + "success": false, + "error": "Could not create new profile document!" + })); + return; + } + //update profile id value in user document + var newProfileDocument = result; + var changeset = { + "profile": newProfileDocument.id + }; + db.merge(req.session.data.user._id, changeset, function(err, result) { + if(err) { + console.log(err); + res.send(200, JSON.stringify({ + "success": false, + "error": "Could not update user document!" + })); + return; + } + db.get(req.session.data.user._id, function(err, doc) { + if(err) { + console.log(err); + res.send(200, JSON.stringify({ + "success": false, + "error": "Could not re-read user document!" + })); + return; + } + //update profile id in session data. + req.session.data.user.profile = newProfileDocument.id; + //send response + res.send(200, JSON.stringify({ + "success": true + })); + }); + }); + }); + }); }); } };