Skip to content

Commit

Permalink
Merge pull request #115 from tahmid-saj/dev-general-cleanup-1
Browse files Browse the repository at this point in the history
moving requests
  • Loading branch information
tahmid-saj authored Jun 13, 2024
2 parents 6f4f50d + d2155f6 commit 25a3d52
Showing 1 changed file with 26 additions and 37 deletions.
63 changes: 26 additions & 37 deletions src/utils/api-requests/recipes.requests.js
Original file line number Diff line number Diff line change
@@ -1,53 +1,42 @@
import { errorOnDisplaySearchedRecipes } from "../errors/recipes.errors";

import { TIMEOUT_SEC } from "../constants/recipes.constants";

// API requests for recipes

// helpers functions

const timeout = (seconds) => {
return new Promise(function (_, reject) {
setTimeout(function () {
reject(new Error(`Request took too long! Timeout after ${seconds} seconds`));
}, seconds * 1000);
});
};

// requests

export const getRecipes = async (recipe) => {
try {
console.log(`${process.env.REACT_APP_RECIPES_URL}${recipe}?${process.env.REACT_APP_RECIPES_API_KEY_NAME}${process.env.REACT_APP_RECIPES_API_KEY}`);
const fetchPromiseRecipes = fetch(`${process.env.REACT_APP_RECIPES_URL}${recipe}?${process.env.REACT_APP_RECIPES_API_KEY_NAME}${process.env.REACT_APP_RECIPES_API_KEY}`)
const resRecipes = await Promise.race([fetchPromiseRecipes, timeout(TIMEOUT_SEC)]);
const dataRecipes = await resRecipes.json();

if (!resRecipes.ok) {
throw new Error(`${dataRecipes.message} (${dataRecipes.status})`);
}

return dataRecipes.data.recipes;
console.log(`${process.env.REACT_APP_API_URL_RECIPES_RECIPES}`)
const response = await fetch(`${process.env.REACT_APP_API_URL_RECIPES_RECIPES}`, {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: String(recipe)
})
const resJSON = await response.json()

return resJSON.recipes
} catch (error) {
errorOnDisplaySearchedRecipes(recipe);
console.log(error);
console.log(error)
errorOnDisplaySearchedRecipes()
}
};

export const getRecipe = async (recipe) => {
try {
const fetchPromiseRecipe = fetch(`${process.env.REACT_APP_RECIPE_URL}${recipe.id}?${process.env.REACT_APP_RECIPES_API_KEY_NAME}${process.env.REACT_APP_RECIPES_API_KEY}`);
const resRecipe = await Promise.race([fetchPromiseRecipe, timeout(TIMEOUT_SEC)]);
const dataRecipe = await resRecipe.json();

if (!resRecipe.ok) {
throw new Error(`${dataRecipe.message} (${dataRecipe.status})`);
}

return dataRecipe.data.recipe;
console.log(`${process.env.REACT_APP_API_URL_RECIPES_RECIPE}`)
const response = await fetch(`${process.env.REACT_APP_API_URL_RECIPES_RECIPE}`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(recipe)
})
const resJSON = await response.json()

return resJSON.recipe
} catch (error) {
errorOnDisplaySearchedRecipes(recipe.title);
console.log(error);
console.log(error)
errorOnDisplaySearchedRecipes()
}
};

0 comments on commit 25a3d52

Please sign in to comment.