constsequelize=newSequelize("database","username","password", { host:"localhost", dialect:"mysql",})sequelize.authenticate().then(() => {console.log("Data Source has been initialized successfully.") }).catch((err) => {console.error("Error during Data Source initialization:", err) })
In TypeORM you create a data source following way:
import { DataSource } from "typeorm"
const dataSource = new DataSource({
type: "mysql",
host: "localhost",
username: "username",
password: "password",
})
dataSource
.initialize()
.then(() => {
console.log("Data Source has been initialized successfully.")
})
.catch((err) => {
console.error("Error during Data Source initialization:", err)
})
Then you can use dataSource instance from anywhere in your app.
In TypeORM these models are called entities and you can define them the following way:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class Project {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
description: string
}
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class Task {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column("text")
description: string
@Column()
deadline: Date
}
It's highly recommended defining one entity class per file. TypeORM allows you to use your classes as database models and provides a declarative way to define what part of your model will become part of your database table. The power of TypeScript gives you type hinting and other useful features that you can use in classes.
In TypeORM there are several ways to create and save a new model:
const employee = new Employee() // you can use constructor parameters as well
employee.name = "John Doe"
employee.title = "senior engineer"
await dataSource.getRepository(Employee).save(employee)