node.js - Create/Update multiple records with one request in Sails.js -
node.js - Create/Update multiple records with one request in Sails.js -
i know best practice create/update multiple records in 1 request. know can using promise.all(). if want tell client records succeeded , failed?
for example, user post like:
{ departmentid: 1, students: [ {name: 'john', studentid: 123}, {name: 'mike', studentid: 124}, ] }
and current solution is:
studentcontroller:
var departmentid = req.param('departmentid'); var poststudents = req.param['students']; var department; var failedrecords = []; department.findone() .then(function (_department) { section = _department; var students = []; while (poststudents.length) { var pupil = poststudents.pop(); student.department = departmentid; var s = student.create(s) .then(function(s){return s;}) .catch(function(e){ failedrecords.push(student)}); // closure problem happens here students.push(s); } homecoming students; }) .each(function (student) { department.students.add(student[0].id); homecoming department.save().catch(function(e){/* log: add together section failed */}); }) .then(function () { homecoming res.json({msg: "success"}); }) .catch(function (e) { homecoming res.json(404, {err: "fail", records: failedrecords}); });
the code ugly, , have omit code solve closure problem in while loop. plus, don't know how save failedrecords in 2nd catch.
i guess sails utilize q library. if not, can convert promise q using q.()
.
so, instead of q.all()
method, have seen q.allsettled()
?
here difference both methods (from q library guide):
the function returns promise array of values. when promise fulfilled, array contains fulfillment values of original promises, in same order promises. if 1 of given promises rejected, returned promise rejected, not waiting rest of batch. if want wait of promises either fulfilled or rejected, can utilize allsettled.
the q.allsettled()
wait promises complete, if 1 or more rejected, , homecoming array of objects like: { state: "fulfilled", value: v } or { state: "rejected", reason: r }
api reference - promise.allsettled()
i'm not sure if best practice inserting in database, because maybe waterline has batch insert mode. i've done in way while posting api insert records , worked fine me.
node.js post promise sails.js waterline
Comments
Post a Comment