Skip to main content

baseRecipeToAdd

async createBaseRecipe(recipe: BaseRecipeDTO, user: User): Promise<BaseRecipe> {

      const baseRecipeToAdd = new BaseRecipe();
      baseRecipeToAdd.title = recipe.title;
      baseRecipeToAdd.category = recipe.category;
      baseRecipeToAdd.created = new Date();
      baseRecipeToAdd.complexRecipes = [];
      const author: User = await this.userService.findById(user.id);
      baseRecipeToAdd.author = author;
      const ingredientArray: Ingredient[] = await this.createIngredients(recipe.ingredients);
      baseRecipeToAdd.ingredients = Promise.all(ingredientArray);

      await this.baseRecipeRepo.save(baseRecipeToAdd);
      return baseRecipeToAdd;
    }

    async createIngredients(ingredientDTOArray: IngredientDTO[]): Promise<Ingredient[]> {
      const ArrToReturn: Ingredient[] = [];
      const productCodes = ingredientDTOArray.map( (ing) => ing.productCode);
      const products: Product[] = await this.productRepository.findByIds(productCodes);
      for (const ingredient of ingredientDTOArray) {
        const ingredientToAdd: Ingredient = new Ingredient();
        ingredientToAdd.baseRecipe = null;
        ingredientToAdd.complexRecipe = null;
        ingredientToAdd.grams = ingredient.grams;
        ingredientToAdd.product = products.filter( (prod) => prod.code === +ingredient.productCode)[0];
        ArrToReturn.push(ingredientToAdd);
        await this.ingredientRepo.save(ingredientToAdd);
      }

      return ArrToReturn;
    }