sauceCtrl_updateSauce

PHOTO EMBED

Wed Sep 08 2021 16:21:57 GMT+0000 (UTC)

Saved by @devdave

exports.updateSauce = (req, res, next) => {

  // if update has to process a new image
  // Ternary Operator | if req.file exists ?
  // => like if() {} else {} => condition checks ? if TRUE : if FALSE
  const sauceObject = req.file
    ? {
        // if exists =>
        // (a) targets all infos from req object
        ...JSON.parse(req.body.sauce),
        // (b) generates new img
        imageUrl: `${req.protocol}://${req.get("host")}/images/${
          req.file.filename
        }`,
      }
    : // if doesn't exist => simply copy req.body
      { ...req.body };

  // [=>] UPDATE / save object
  // [1] _id = param Req id
  // [2] new object version = targets param Req sauce / _id = param Req id
  Sauce.updateOne(
    { _id: req.params.id },
    { ...sauceObject, _id: req.params.id }
  )
    .then(() => res.status(200).json({ message: "Objet modifié !" }))
    .catch((error) => res.status(400).json({ error }));
};
content_copyCOPY