-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathSpoonableAPI.js
More file actions
96 lines (68 loc) · 2.54 KB
/
Copy pathSpoonableAPI.js
File metadata and controls
96 lines (68 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const fetch = require('node-fetch-npm');
const Recipe = require('./Recipe');
class SpoonableAPI {
constructor() {
this.api_key = "4f8dacc258c84b57be1e22d613b58736";
this.name = "https://api.spoonacular.com/";
}
async findRecipeByIngredients(ingredients) {
const url = `${this.name}recipes/findByIngredients?ingredients=${ingredients.join(",+")}&number=2&apiKey=${this.api_key}`;
const filePath = "recipes.json";
try {
const response = await fetch(url);
const data = await response.json();
const recipeMap = {};
data.forEach(recipe => {
recipeMap[recipe.title] = recipe.id;
});
return recipeMap;
} catch (error) {
console.error(error);
return {};
}
}
async getRecipeInfo(id) {
const finalUrl = `${this.name}recipes/${id}/information?includeNutrition=false&addWinePairing=false&addTasteData=false&apiKey=${this.api_key}`;
console.log('Fetching recipe information from:', finalUrl);
try {
const response = await fetch(finalUrl);
if (!response.ok) {
throw new Error('Failed to fetch recipe information');
}
const data = await response.json();
// Create Recipe object
const recipe = new Recipe(data);
return recipe;
} catch (error) {
console.error('Error fetching recipe information:', error);
return null; // Return null or any other appropriate value to indicate failure
}
}
async searchRecipe(query) {
const url = `${this.name}recipes/complexSearch?query=${query}&maxFat=25&number=2&apiKey=${this.api_key}`;
try {
const response = await fetch(url);
const data = await response.json();
const recipeMap = {};
data.results.forEach(recipe => {
recipeMap[recipe.title] = recipe.id;
});
return recipeMap;
} catch (error) {
console.error(error);
return {};
}
}
}
module.exports = SpoonableAPI;
// Example usage
const spoonableAPI = new SpoonableAPI();
spoonableAPI.findRecipeByIngredients(["apple", "banana"]).then(recipeMap => {
console.log(recipeMap);
});
spoonableAPI.searchRecipe("pasta").then(recipeMap => {
console.log(recipeMap);
});
spoonableAPI.getRecipeInfo(638604).then(recipe => {
recipe.print();
});