chore: change seed script to use compiled JS instead of ts-node

- Update package.json to run node scripts/seed.js instead of ts-node scripts/seed.ts
- Rewrite seed.js to use compiled model from dist/ directory and Sequelize directly
- Add proper error handling and database connection setup
- Ensure script works after build, requiring npm run build first
This commit is contained in:
Jp
2026-02-02 16:34:17 +08:00
parent 0999d46bd0
commit e16e3ec387
2 changed files with 47 additions and 8 deletions

View File

@@ -7,7 +7,7 @@
"build": "tsc",
"start": "node dist/main.js",
"start:dev": "nodemon --watch 'src/**/*.ts' --exec \"ts-node\" src/main.ts",
"seed": "ts-node scripts/seed.ts"
"seed": "node scripts/seed.js"
},
"dependencies": {
"@nestjs/common": "^11.1.12",
@@ -45,4 +45,4 @@
"ts-node": "^10.9.2",
"typescript": "^5.9.3"
}
}
}

View File

@@ -1,4 +1,39 @@
const db = require('../models');
const { Sequelize } = require('sequelize-typescript');
const path = require('path');
const fs = require('fs');
// Try to find the model file
let FoodItem;
const distModelPath = path.join(__dirname, '../dist/models/food-item.model.js');
if (fs.existsSync(distModelPath)) {
const modelModule = require(distModelPath);
FoodItem = modelModule.FoodItem;
} else {
console.error('Could not find compiled FoodItem model at ' + distModelPath);
console.error('Please run "npm run build" first.');
process.exit(1);
}
// Database connection
const dbPath = process.env.DATABASE_URL
? process.env.DATABASE_URL.replace('sqlite://', '')
: path.join(__dirname, '../data/calorie_tracker.db');
// Ensure data directory exists if using sqlite file
if (!process.env.DATABASE_URL) {
const dataDir = path.dirname(dbPath);
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
}
}
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: dbPath,
models: [FoodItem],
logging: false
});
const filipinoFoods = [
// Rice (Kanin)
@@ -440,13 +475,17 @@ const filipinoFoods = [
async function seed() {
try {
await db.sequelize.sync();
await sequelize.authenticate();
console.log('Database connection has been established successfully.');
// Sync database (create tables if not exists)
await sequelize.sync();
let addedCount = 0;
for (const foodData of filipinoFoods) {
// Check if already exists
const existing = await db.FoodItem.findOne({
const existing = await FoodItem.findOne({
where: {
name: foodData.name,
is_filipino: true
@@ -454,7 +493,7 @@ async function seed() {
});
if (!existing) {
await db.FoodItem.create({
await FoodItem.create({
...foodData,
source: 'filipino',
is_filipino: true
@@ -467,8 +506,8 @@ async function seed() {
} catch (error) {
console.error('Error seeding Filipino foods:', error);
} finally {
await db.sequelize.close();
await sequelize.close();
}
}
seed();
seed();