generated from chingu-voyages/voyage-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAPI2db.js
85 lines (74 loc) · 2.4 KB
/
API2db.js
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
// fetch data from an API
const apiURL = "https://menus-api.vercel.app/";
fetch(apiURL)
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json();
})
.then((data) => {
insertData(data);
})
.catch((error) => {
console.log("Error:", error);
});
// insert data into the database
const db = require('../models');
async function insertData(data) {
try {
await db.sequelize.sync({ force: true });
console.log("Database synced successfully.");
const categories = Object.keys(data.pagination);
for (let categoryName of categories) {
let [categoryRecord, created] = await db.Category.findOrCreate({
where: { name: categoryName },
defaults: { name: categoryName }
});
for (let item of data[categoryName]) {
// restaurant data
let restaurant = {
name: item.name,
country: item.country,
latitude: item.latitude,
longitude: item.longitude,
};
// fooditem data
let foodItem = {
name: item.dsc,
imageUrl: item.img,
price: item.price,
};
// add restaurant to database if not there
let [restaurantRecord, restaurantCreated] = await db.Restaurant.findOrCreate({
where: { name: restaurant.name },
defaults: restaurant
});
// add foodItem to database if not there
let [foodItemRecord, foodItemCreated] = await db.FoodItem.findOrCreate({
where: { name: foodItem.name, restaurantId: restaurantRecord.id },
defaults: {
name: foodItem.name,
imageUrl: foodItem.imageUrl,
price: foodItem.price,
restaurantId: restaurantRecord.id
}
});
// create association in FoodItemCategory table
await db.FoodItemCategory.findOrCreate({
where: {
foodItemId: foodItemRecord.id,
categoryId: categoryRecord.id
},
defaults: {
foodItemId: foodItemRecord.id,
categoryId: categoryRecord.id
}
});
console.log('Inserted:', { restaurant, category: categoryRecord, foodItem });
}
}
} catch (error) {
console.log('Error:', error);
}
}