Tuesday 29 January 2019

Sequelize+Expressjs question

Long time Rails dev looking to expand my backend portfolio and am building a small side project that's supposed to be a meal planner. Basically, its an app to spit out 5 random recipes per week with grocery lists.I'm working on the recipe endpoint as I'll allow a user to create a recipe to save that they will later cook when it comes up. In post, a user should create a brand new Recipe { name and instructions } and hasMany ingredients. An Ingredient has { quantity } and belongsTo an IngredientType which has { name, unit }.A user should be able to submit a recipe with ingredients(always created) and can either create a corresponding ingredient type or find one with the exact same combo of name/unit.My goal is to make this into 1 transaction so that if any validations fail, the whole transaction fails. Here is my current code:router.post("/", (req: Request, res: Response) => { const { name, instructions } = req.body.recipe; db.Recipe.create({ name, instructions }) .then(async recipe => { const ingredients: IngredientInstance[] = await req.body.recipe.ingredients.map((ingredient: any) => { const { quantity, ingredient_type } = ingredient; const { id, name, unit } = ingredient_type; db.Ingredient.create({ quantity }) .then(async ingredient => { const [ingredientType, ] = await db.IngredientType .findOrCreate({ where: { id, name: name.toLowerCase(), unit }}) await ingredient.setIngredientType(ingredientType.id); await ingredient.setRecipe(recipe.id); return ingredient }) }); return recipe; }) .then(recipe => res.status(201).json({ recipe })) }); This is obviously several transactions. The recipe is created, then every ingredient is created. I'm not sure how to make this one transaction though.

Submitted January 30, 2019 at 02:33AM by boboguitar

No comments:

Post a Comment