UNPKG

dm-tools

Version:
73 lines (65 loc) 1.91 kB
import {Sequelize, DataTypes, Model} from 'sequelize'; import assert from 'node:assert/strict'; // Define Student data model. export class Student extends Model { // declaring fileds are optional, more for documenting was db columns are defined. // NOTE: removing 'declare' will cause shadowing for getter/setter. declare id: number; declare name: string; declare surname: string; declare email: string; } export function initStudentModel(sequelize: Sequelize) { // Define Student model properties. // Columns: id, createdAt, updatedAt will be automatically created. // Database table name is defined explicitly. Student.init( { name: { type: DataTypes.STRING, allowNull: false, }, surname: { type: DataTypes.STRING, allowNull: false, }, email: { type: DataTypes.STRING, allowNull: false, }, }, { sequelize, tableName: 'students', }, ); } export async function createStudentTable(sequelize: Sequelize) { // Drop all table if exist, create all tables. // Calling sync always made the database table match the model. await sequelize.sync({force: true}); // // All models are available through "sequelize.models". assert(sequelize.models.Student == Student); // // Insert values into Students table. await Student.create({ name: 'Rajinder', surname: 'Yadav', email: 'ry@home.net', }); await Student.create({ name: 'Tammy', surname: 'Trinh', email: 'tammy@test.ca', }); await Student.create({ name: 'Shivaji', surname: 'Yadav', email: 'shivaji@dev.com', }); } export async function getAllStudents() { // findAll() will accept the following argument to filter columns. // { attributes: ['id', 'name', 'surname'] } const students = await Student.findAll(); students.forEach((s) => console.log(s.dataValues)); }