package spoonaccular; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.cdimascio.dotenv.Dotenv; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.springframework.stereotype.Component; import spoonaccular.models.recipe_by_ingredient.ExtendedRecipeByIngredient; import spoonaccular.models.recipe_by_ingredient.RecipeByIngredient; import spoonaccular.models.recipe_information.Recipe; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; @Component public class RecipeInformation { private final static Dotenv dotenv = Dotenv.configure().ignoreIfMissing().ignoreIfMalformed().load(); private final static OkHttpClient client = new OkHttpClient(); private RecipeInformation(){ } public static List getRecipeFromIds(List ids) throws IOException { String idsString = ids.stream().map(String::valueOf) .collect(Collectors.joining(",")); return new ObjectMapper().readValue(queryInformationBulk(idsString).body().string(), new TypeReference<>(){}); } public static List getExtendedRecipeFromIds(List ids) throws IOException { String idsString = ids.stream().map(String::valueOf) .collect(Collectors.joining(",")); return new ObjectMapper().readValue(queryInformationBulk(idsString).body().string(), new TypeReference<>() {}); } private static Response queryInformationBulk(String idsString) throws IOException { Request request = APIAuthentication.addAuthHeaders(new Request.Builder() .url("https://" + dotenv.get("X-RapidAPI-Host") + "/recipes/informationBulk?ids=" + idsString)) .build(); return client.newCall(request).execute(); } public static List getRecepieByIngredientsExtended(List recipeByIngredients) throws IOException { List ids = recipeByIngredients.stream().map(RecipeByIngredient::getId).toList(); List extendedRecipeByIngredients = getExtendedRecipeFromIds(ids); Iterator recipeByIngredientIterator = recipeByIngredients.iterator(); Iterator extendedRecipeByIngredientIterator = extendedRecipeByIngredients.iterator(); while(recipeByIngredientIterator.hasNext() && extendedRecipeByIngredientIterator.hasNext()){ extendedRecipeByIngredientIterator.next().addMissingInfo(recipeByIngredientIterator.next()); } return extendedRecipeByIngredients; } }