Guest User

Untitled

a guest
Sep 20th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. /**
  2. * Updating the state of cartRecipes table (holds cartId, recipeId and amount).
  3. * Shows the creation of dynamic insert statement by using a reduce function.
  4. *
  5. * Note: This was taken out of context for demonstational purposes therefore
  6. * some imports might be missing.
  7. */
  8.  
  9. function updateCartRecipes(cartId, recipes) {
  10.  
  11. if (cartId) {
  12.  
  13. try {
  14.  
  15. // First delete all recipes with the given cart id
  16. await databaseService.query(`DELETE FROM cartRecipes WHERE cartId = ${cartId}`);
  17.  
  18. if (recipes.length > 0) {
  19.  
  20. // Create a dynamic insert statement to insert multiple recipes at once
  21. const insertQuery = await databaseService.query(`
  22. INSERT INTO cartRecipes (recipeId, cartId, amount)
  23. VALUES ${payload.recipes.reduce((prev, cur) => `${prev ? (prev + ',') : prev} (${cur.id}, ${cartId}, ${cur.amount})`, '')}`);
  24.  
  25. return insertQuery.success;
  26. }
  27.  
  28. return true;
  29.  
  30. } catch (e) {
  31. logger.error(e);
  32. return false;
  33. }
  34. }
  35. }
Add Comment
Please, Sign In to add comment