Guest User

Untitled

a guest
Jan 16th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. router.put('/:id', authorize(), async (req, res, next) => {
  2. // Destructure objects and lists as separate variables to be used in list updaters
  3. const {
  4. params: { id },
  5. body: {
  6. params: {
  7. guide: passedGuide,
  8. sections: passedSections,
  9. },
  10. },
  11. } = req;
  12. // The spread function is like .complete, but works with lists of objects.
  13. const guide = (id === 'create')
  14. ? await Guide.create(passedGuide)
  15. : await Guide.find({ where: { id }, includes: [Section] });
  16. guide.update(passedGuide);
  17. // simple maps on lists of objects into Sequelize calls. Anything more complicated should be
  18. // pulled out into another invocation
  19. await Promise.all(passedSections.map(passedSection => (
  20. Section.findOrCreate({
  21. // you need all database-required params in this where clause, otherwise it'll fail
  22. // I'd love to see more use of required fields at the database level, easiest way to
  23. // ensure clean data
  24. where: {
  25. id: passedSection.id,
  26. guide_id: guide.id,
  27. type: passedSection.type,
  28. order: passedSection.order,
  29. },
  30. }).spread(s => s.update({ ...passedSection }))
  31. )));
  32. // This doesn't facilitate section deletions. Need another query
  33. // to grab all sections and remove the ones that weren't passed.
  34. guide.getGuides_sections().spread((section) => {
  35. const found = _.find(passedSections, passedSection => (
  36. passedSection.id === section.id
  37. ));
  38. if (typeof found === 'undefined') { section.destroy(); }
  39. });
  40. res.send(GuideView.get(guide));
  41. return next();
  42. });
Add Comment
Please, Sign In to add comment