Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- router.put('/:id', authorize(), async (req, res, next) => {
- // Destructure objects and lists as separate variables to be used in list updaters
- const {
- params: { id },
- body: {
- params: {
- guide: passedGuide,
- sections: passedSections,
- },
- },
- } = req;
- // The spread function is like .complete, but works with lists of objects.
- const guide = (id === 'create')
- ? await Guide.create(passedGuide)
- : await Guide.find({ where: { id }, includes: [Section] });
- guide.update(passedGuide);
- // simple maps on lists of objects into Sequelize calls. Anything more complicated should be
- // pulled out into another invocation
- await Promise.all(passedSections.map(passedSection => (
- Section.findOrCreate({
- // you need all database-required params in this where clause, otherwise it'll fail
- // I'd love to see more use of required fields at the database level, easiest way to
- // ensure clean data
- where: {
- id: passedSection.id,
- guide_id: guide.id,
- type: passedSection.type,
- order: passedSection.order,
- },
- }).spread(s => s.update({ ...passedSection }))
- )));
- // This doesn't facilitate section deletions. Need another query
- // to grab all sections and remove the ones that weren't passed.
- guide.getGuides_sections().spread((section) => {
- const found = _.find(passedSections, passedSection => (
- passedSection.id === section.id
- ));
- if (typeof found === 'undefined') { section.destroy(); }
- });
- res.send(GuideView.get(guide));
- return next();
- });
Add Comment
Please, Sign In to add comment