Ver código fonte

Update ingredient creation code to work with new session id.

Lee Morgan 5 anos atrás
pai
commit
d5d124e023
2 arquivos alterados com 14 adições e 16 exclusões
  1. 8 2
      app.js
  2. 6 14
      controllers/ingredientData.js

+ 8 - 2
app.js

@@ -8,7 +8,8 @@ const Merchant = require("./models/merchant.js");
 const helper = require("./controllers/helper.js");
 
 let protectedRoutes = [
-    "/dashboard"
+    "/dashboard",
+    "/ingredients/create"
 ];
 
 const app = express();
@@ -43,7 +44,11 @@ app.use(session({
 }));
 app.use((req, res, next)=>{
     if(protectedRoutes.includes(req.url)){
-        if(req.session.user === undefined) return res.redirect("/");
+        if(req.session.user === undefined) {
+            req.session.error = "PLEASE LOG IN";
+            return res.redirect("/");
+        }
+
         Merchant.findOne({"session.sessionId": req.session.user})
             .then((merchant)=>{
                 if(merchant === null){
@@ -65,6 +70,7 @@ app.use((req, res, next)=>{
             })
             .catch((err)=>{
                 if(err === "no merchant"){
+                    req.session.error = "PLEASE LOG IN";
                     return res.redirect("/");
                 }
                 return res.json("ERROR: UNABLE TO RETRIEVE DATA");

+ 6 - 14
controllers/ingredientData.js

@@ -23,33 +23,25 @@ module.exports = {
         Same as above, with the _id
     */
     createIngredient: function(req, res){
-        if(!req.session.user){
-            req.session.error = "MUST BE LOGGED IN TO DO THAT";
-            return res.redirect("/");
-        }
-
         let newIngredient = {...req.body};
         if(req.body.defaultUnit === "bottle"){
             newIngredient.ingredient.unitSize = helper.convertQuantityToBaseUnit(newIngredient.ingredient.unitSize, newIngredient.ingredient.unitType);
         }
 
         newIngredient = new Ingredient(newIngredient.ingredient);
-
-        let ingredientPromise = newIngredient.save();
-        let merchantPromise = Merchant.findOne({_id: req.session.user});
-
-        Promise.all([ingredientPromise, merchantPromise])
-            .then((response)=>{
+        
+        newIngredient.save()
+            .then((ingredient)=>{
                 newIngredient = {
-                    ingredient: response[0],
+                    ingredient: ingredient,
                     defaultUnit: req.body.defaultUnit
                 }
 
                 newIngredient.quantity = helper.convertQuantityToBaseUnit(req.body.quantity, req.body.defaultUnit);
 
-                response[1].inventory.push(newIngredient);
+                res.locals.merchant.inventory.push(newIngredient);
 
-                return response[1].save();
+                return res.locals.merchant.save();
             })
             .then((response)=>{
                 return res.json(newIngredient);