import { Sequelize, QueryTypes, DataTypes } from "sequelize";
const sequelize = new Sequelize("sqlite::memory:", {
pool: {
max: 5, // max conns.; default 5
min: 0, // min conns.; default 0
acquire: 30000, // maximum time (in ms) that a connection can be idle before throwing an error; default 30000
idle: 10000, // max time (in ms) that a connection can be idle before being released; default 10000
},
});
console.log("LOADING: inside db.ts");
export const populateDb = async () => {
try {
console.log("START: creating table(s)");
const User = sequelize.define(
"User",
{
userKey: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
username: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
freezeTableName: true, // enforces that table name = model name
}
);
// sync method creates table
await User.sync({ force: true });
console.log("COMPLETE: table(s) (re)created");
console.log("START: populating database");
// statement: sequelize.models.User === User
const u1 = await sequelize.models.User.create({
username: "gary",
name: "Gary",
});
const u2 = await sequelize.models.User.create({
username: "chris",
name: "Christine",
});
console.log("COMPLETE: database populated");
return true;
} catch {
console.log("FAILURE: did not populate database");
return false;
}
};
async () => await populateDb();
export default sequelize;
I’m trying to run populateDb() when the module first loads via my import. Attempting to run the async func. isn’t working in my example.
I only need it to load once and of course on reloads. Is there a way to do this? Ideally, I’d like to wait until until sequelize fully loads, but I don’t see any hooks in the documentation to allow for this.