const { Sequelize } =require('sequelize');constdotenv=require("dotenv"); // Import dotenvdotenv.config(); // Load environment variables from .env file// Initialize Sequelize with your MySQL connection detailsconst { DB_USER,DB_PASS,DB_HOST } =process.env;constsequelize=newSequelize('db_name',DB_USER,DB_PASS, { host:DB_HOST, dialect:'mysql', logging:false,});module.exports= sequelize;
2.創建 /database/models/user.js
const { DataTypes } =require('sequelize');constsequelize=require('../connect');constUser=sequelize.define('User', { id: { type:DataTypes.UUID, defaultValue:DataTypes.UUIDV4, primaryKey:true, allowNull:false, }, createdAt: { type:DataTypes.DATE, allowNull:false, defaultValue:sequelize.literal('CURRENT_TIMESTAMP'),// Set the default value to the current timestamp },});module.exports= User;
constexpress=require("express");constapp=express();constsequelize=require("./database/connect.js");// 在這裡記得引入 schema,他才會知道到要創 tablerequire("./database/models/user");require("./database/models/userReward");asyncfunctioninitDatabase() {try {awaitsequelize.authenticate();awaitsequelize.sync({ force:false }); // {alter: true}console.log("Database synced")// Additional model-related initialization can go here } catch (err) {console.error('Failed to initialize database:', err);throw err; }}constinitRoute=async () => {constuserRoute=require("./router/user");// Routerapp.use(`/user`, userRoute);};constserver=app.listen(port,function (err) {if (err) {console.log(err); } else {console.log("Listening on port "+ port); }});asyncfunctionmain() {try {awaitinitDatabase();awaitinitRoute() } catch (err) {console.error('Application initialization failed:', err); }}main();module.exports= { server,};