I have an Express application, PostgreSQL is used as a database, and Sequelize is used as an ORM.
I connect to the database as follows:
import { Sequelize } from "sequelize-typescript";
import "dotenv/config";
export const sequelize = new Sequelize({
database: process.env.DB_NAME,
dialect: "postgres",
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
host: process.env.DB_HOST,
port: Number(process.env.DB_PORT),
models: [__dirname + "/models/**"]
});
And this is how I describe my models:
import { Table, Column, Model, DataType, ForeignKey, HasMany } from 'sequelize-typescript';
import Message from './Message';
@Table({
timestamps: false,
tableName: "message_types"
})
class MessageType extends Model {
@Column({
type: DataType.STRING,
})
type: string;
@HasMany(() => Message, {
onDelete: 'CASCADE'
})
messages: Message[];
}
export default MessageType;
Question: how can I do to automatically fill the database table with standard values initially? for example, fill the message_types table with the values: Default, Deleted, System, Voice, Video.
Now it works for me as follows: when the application is started, the initMessageTypes method of the MessageTypeService service is called:
import { Op } from "sequelize";
import MessageType from "../../db/models/messenger/MessageType";
import { MessageTypes } from "types/messenger";
const initialTypes: string[] = [
MessageTypes.Default,
MessageTypes.Deleted,
MessageTypes.System,
MessageTypes.Voice,
MessageTypes.Video
];
class MessageTypeService {
async initMessageTypes() {
initialTypes.forEach(async (type) => {
const existedType = await MessageType.findOne({
where: {
type
}
});
if (!existedType) {
await MessageType.create({
type
});
}
});
return await MessageType.destroy({
where: {
type: {
[Op.notIn]: initialTypes
}
}
});
}
}
export default new MessageTypeService();