Guest User

Untitled

a guest
Sep 20th, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.88 KB | None | 0 0
  1. /**
  2. * These methods display fetching data from a MySQL database.
  3. * Single row from main table and multiple rows from secondary tables.
  4. * All results are coupled together into an object before sending the response.
  5. *
  6. * Example response: {
  7. * success: true,
  8. * data: {
  9. * name: 'IngredientName',
  10. * description: 'IngredientDescription',
  11. * photo: 'IngredientPhoto',
  12. * category: 'IngredientCategory',
  13. * allowedUnits: [...],
  14. * allergents: [...],
  15. * nutrients: [...]
  16. * }
  17. * }
  18. *
  19. * Note: This was taken out of context for demonstational purposes therefore
  20. * some imports might be missing.
  21. */
  22.  
  23. function getIngredient(id) {
  24. return Promise.all([
  25. databaseService.singleQuery(`
  26. SELECT
  27. ingredients.id AS id,
  28. ingredients.name AS name,
  29. ingredients.description AS description,
  30. ingredients.photo AS photo,
  31. categories.name AS category
  32. FROM ingredients
  33. LEFT JOIN ingredientCategories ON ingredientCategories.ingredientId = ingredients.id
  34. LEFT JOIN categories ON categories.id = ingredientCategories.categoryId
  35. WHERE ingredients.id = ${id}
  36. `),
  37. databaseService.query(`
  38. SELECT
  39. units.id AS id,
  40. units.shortName AS shortName,
  41. units.longName AS longName
  42. FROM ingredientAllowedUnits
  43. LEFT JOIN units ON units.id = ingredientAllowedUnits.unitId
  44. WHERE ingredientId = ${id}
  45. `),
  46. databaseService.query(`
  47. SELECT
  48. allergents.id AS id,
  49. allergents.name AS name
  50. FROM ingredientAllergents
  51. LEFT JOIN allergents ON allergents.id = ingredientAllergents.allergentId
  52. WHERE ingredientId = ${id}
  53. `),
  54. databaseService.query(`
  55. SELECT
  56. nutrients.id AS id,
  57. nutrients.name AS name,
  58. ingredientNutrients.value AS value
  59. FROM ingredientNutrients
  60. LEFT JOIN nutrients ON nutrients.id = ingredientNutrients.nutrientId
  61. WHERE ingredientId = ${id}
  62. `)
  63. ]);
  64. }
  65.  
  66. async function getIngredientHook(request, response) {
  67.  
  68. // Authenticate user (returns user object or null)
  69. const user = await authenticationService.checkUserSession(request, response);
  70.  
  71. if (user) {
  72.  
  73. // Check if ingredient id was succesfully passed in the url
  74. if (!request.params || !request.params.id) {
  75. response.send(responseService.formatResponseError('Ingredient ID is required!'));
  76. return;
  77. }
  78.  
  79. const ingredientId = request.params.id;
  80.  
  81. try {
  82. const ingredientData = await ingredientsService.getIngredient(ingredientId);
  83.  
  84. // ingredientData[0].success && ingredient[0].data checks if initial ingredient query was succesful and returned a non-null response
  85. if (ingredientData && ingredientData[0].success && ingredientData[0].data) {
  86.  
  87. // Ingredient query response (first) (returns object - single row)
  88. let ingredient = ingredientData[0].success ? ingredientData[0].data : {};
  89.  
  90. // Allowed units query response (second) (returns array of objects - multiple rows)
  91. const allowedUnits = ingredientData[1].success ? ingredientData[1].data : [];
  92.  
  93. // Allergents query response (third) (returns array of objects - multiple rows)
  94. const allergents = ingredientData[2].success ? ingredientData[2].data : [];
  95.  
  96. // Nutrients query response (fourth) (returns array of objects - multiple rows)
  97. const nutrients = ingredientData[3].success ? ingredientData[3].data : [];
  98.  
  99. // Combine query responses into an object (nicely formatted)
  100. ingredient = Object.assign(ingredient, { allowedUnits, allergents, nutrients });
  101.  
  102. response.send(responseService.formatResponseData(ingredient));
  103.  
  104. // If ingredientData[0].data is null then no rows have been found with the supplied ID
  105. } else if (ingredientData && !ingredientData[0].data) {
  106. response.send(responseService.formatResponseError(`Ingredient with id ${ingredientId} not found.`));
  107.  
  108. // Return error in other cases
  109. } else {
  110. logger.error(ingredientData);
  111. response.send(responseService.formatResponseError('Error fetching ingredient, contact system administrator!'));
  112. }
  113. } catch (e) {
  114. logger.error(e);
  115. response.send(responseService.formatResponseError('Error fetching ingredient, contact system administrator!'));
  116. }
  117. }
  118. };
Add Comment
Please, Sign In to add comment