Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * These methods display fetching data from a MySQL database.
- * Single row from main table and multiple rows from secondary tables.
- * All results are coupled together into an object before sending the response.
- *
- * Example response: {
- * success: true,
- * data: {
- * name: 'IngredientName',
- * description: 'IngredientDescription',
- * photo: 'IngredientPhoto',
- * category: 'IngredientCategory',
- * allowedUnits: [...],
- * allergents: [...],
- * nutrients: [...]
- * }
- * }
- *
- * Note: This was taken out of context for demonstational purposes therefore
- * some imports might be missing.
- */
- function getIngredient(id) {
- return Promise.all([
- databaseService.singleQuery(`
- SELECT
- ingredients.id AS id,
- ingredients.name AS name,
- ingredients.description AS description,
- ingredients.photo AS photo,
- categories.name AS category
- FROM ingredients
- LEFT JOIN ingredientCategories ON ingredientCategories.ingredientId = ingredients.id
- LEFT JOIN categories ON categories.id = ingredientCategories.categoryId
- WHERE ingredients.id = ${id}
- `),
- databaseService.query(`
- SELECT
- units.id AS id,
- units.shortName AS shortName,
- units.longName AS longName
- FROM ingredientAllowedUnits
- LEFT JOIN units ON units.id = ingredientAllowedUnits.unitId
- WHERE ingredientId = ${id}
- `),
- databaseService.query(`
- SELECT
- allergents.id AS id,
- allergents.name AS name
- FROM ingredientAllergents
- LEFT JOIN allergents ON allergents.id = ingredientAllergents.allergentId
- WHERE ingredientId = ${id}
- `),
- databaseService.query(`
- SELECT
- nutrients.id AS id,
- nutrients.name AS name,
- ingredientNutrients.value AS value
- FROM ingredientNutrients
- LEFT JOIN nutrients ON nutrients.id = ingredientNutrients.nutrientId
- WHERE ingredientId = ${id}
- `)
- ]);
- }
- async function getIngredientHook(request, response) {
- // Authenticate user (returns user object or null)
- const user = await authenticationService.checkUserSession(request, response);
- if (user) {
- // Check if ingredient id was succesfully passed in the url
- if (!request.params || !request.params.id) {
- response.send(responseService.formatResponseError('Ingredient ID is required!'));
- return;
- }
- const ingredientId = request.params.id;
- try {
- const ingredientData = await ingredientsService.getIngredient(ingredientId);
- // ingredientData[0].success && ingredient[0].data checks if initial ingredient query was succesful and returned a non-null response
- if (ingredientData && ingredientData[0].success && ingredientData[0].data) {
- // Ingredient query response (first) (returns object - single row)
- let ingredient = ingredientData[0].success ? ingredientData[0].data : {};
- // Allowed units query response (second) (returns array of objects - multiple rows)
- const allowedUnits = ingredientData[1].success ? ingredientData[1].data : [];
- // Allergents query response (third) (returns array of objects - multiple rows)
- const allergents = ingredientData[2].success ? ingredientData[2].data : [];
- // Nutrients query response (fourth) (returns array of objects - multiple rows)
- const nutrients = ingredientData[3].success ? ingredientData[3].data : [];
- // Combine query responses into an object (nicely formatted)
- ingredient = Object.assign(ingredient, { allowedUnits, allergents, nutrients });
- response.send(responseService.formatResponseData(ingredient));
- // If ingredientData[0].data is null then no rows have been found with the supplied ID
- } else if (ingredientData && !ingredientData[0].data) {
- response.send(responseService.formatResponseError(`Ingredient with id ${ingredientId} not found.`));
- // Return error in other cases
- } else {
- logger.error(ingredientData);
- response.send(responseService.formatResponseError('Error fetching ingredient, contact system administrator!'));
- }
- } catch (e) {
- logger.error(e);
- response.send(responseService.formatResponseError('Error fetching ingredient, contact system administrator!'));
- }
- }
- };
Add Comment
Please, Sign In to add comment