From 8c399384c3332cf0d977b67b842cfc503b1c3289 Mon Sep 17 00:00:00 2001 From: Remi REGNAULT Date: Fri, 1 Dec 2023 08:28:25 +0100 Subject: [PATCH] feat: add route multiples ingredients to find a recipe --- .../src/controllers/recipes.controller.ts | 26 ++++++++++++++++ API-Project/src/gateways/recipe.gateway.ts | 30 +++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/API-Project/src/controllers/recipes.controller.ts b/API-Project/src/controllers/recipes.controller.ts index 74639a8..a716874 100644 --- a/API-Project/src/controllers/recipes.controller.ts +++ b/API-Project/src/controllers/recipes.controller.ts @@ -40,4 +40,30 @@ RecipesController.get('/:id', async (req, res) => { } }) +RecipesController.get('/withingr/:ids', async (req, res) => { + let ids: number[] = []; + let raw_ids = String(req.params.ids).split(':') + for (let key in raw_ids) { + const test = Number(raw_ids[key]) + if (Number.isNaN(test) || !Number.isInteger(test)) { + res.status(400).json('A parameter is not an integer') + } + ids.push(Number(test)) + } + + try { + const recipes = await recipes_gw.getIdsRecipesThatContainsIngredients(ids) + + if (recipes.length == 0) { + res.status(404).json('no data found') + } + else { + res.status(200).json(recipes) + } + } catch (error) { + const error_error = error as Error + res.status(500).send(error_error.message) + } +}) + export { RecipesController } \ No newline at end of file diff --git a/API-Project/src/gateways/recipe.gateway.ts b/API-Project/src/gateways/recipe.gateway.ts index c245ea0..a087d84 100644 --- a/API-Project/src/gateways/recipe.gateway.ts +++ b/API-Project/src/gateways/recipe.gateway.ts @@ -58,4 +58,34 @@ export class RecipeGateway { return recipe; } + + async getIdsRecipesThatContainsIngredients(ids: number[]) : Promise { + let recipes: Recipe[] = [] + + const client = await this.connection.getPoolClient() + + let query_list_text = '($1' + for (let count = 1; count < ids.length; count++) { + query_list_text = query_list_text + ', $' + String(count+1) + } + query_list_text = query_list_text + ')' + + const query = { + text: 'SELECT idRecipe FROM Composed GROUP BY idRecipe HAVING COUNT(DISTINCT idIngredient) = COUNT(DISTINCT CASE WHEN idIngredient IN ' + query_list_text + ' THEN idIngredient END)', + values: ids + } + + const res = await client.query(query) + + client.release() + + for(var key in res.rows) { + const recipe = await this.getById(Number(res.rows[key].idrecipe)) + if (recipe != null) { + recipes.push(recipe) + } + } + + return recipes + } } \ No newline at end of file