-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddExampleData.js
More file actions
41 lines (33 loc) · 1.13 KB
/
addExampleData.js
File metadata and controls
41 lines (33 loc) · 1.13 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
import { readFileSync } from 'fs';
import sequelize from './config/database.js';
import { Product } from './models/index.js';
async function setupDatabase() {
try {
// Drop the table if it exists
await Product.drop();
console.log('Existing tables dropped.');
// Wait for all models to synchronize with the database
await sequelize.sync({ force : true });
console.log('Database synced.');
// Now add example data
await addExampleData();
}
catch (error) {
console.error('Failed to setup database: ', error);
}
}
async function addExampleData() {
try {
// Read and parse the JSON data
const productsData = JSON.parse(readFileSync('example-data/products.json'));
await sequelize.transaction(async(t) => {
const products = await Product.bulkCreate(productsData, { transaction : t });
return { products };
});
console.log('Products added to database successfully.');
}
catch (error) {
console.error('Failed to add data to database due to an error: ', error);
}
}
setupDatabase();