[英]How to use TypeScript with Sequelize when targeting ESM
[英]How to use TypeScript with Sequelize
我已經使用 Fastify 用 Node、PostgreSQL、Sequelize 編寫了我的服務器應用程序。
現在我想使用 TypeScript。 誰能告訴我如何開始使用 TypeScript 重寫我的服務器應用程序。
使用裝飾器是你應該盡可能避免的事情,它們不是 ECMAScript 標准。 他們甚至被視為遺產。 這就是為什么我要向您展示如何在打字稿中使用 sequelize。
我們只需要遵循文檔: https : //sequelize.org/v5/manual/typescript.html但因為它不是很清楚,或者至少對我來說。 我花了一段時間才明白。
那里說你需要安裝這棵樹的東西
* @types/node
* @types/validator // this one is not need it
* @types/bluebird
npm i -D @types/node @types/bluebird
那么讓我們假設您的項目如下所示:
myProject
--src
----models
------index.ts
------user-model.ts
------other-model.ts
----controllers
----index.ts
--package.json
讓我們先創建用戶模型
`./src/models/user-model.ts`
import { BuildOptions, DataTypes, Model, Sequelize } from "sequelize";
export interface UserAttributes {
id: number;
name: string;
email: string;
createdAt?: Date;
updatedAt?: Date;
}
export interface UserModel extends Model<UserAttributes>, UserAttributes {}
export class User extends Model<UserModel, UserAttributes> {}
export type UserStatic = typeof Model & {
new (values?: object, options?: BuildOptions): UserModel;
};
export function UserFactory (sequelize: Sequelize): UserStatic {
return <UserStatic>sequelize.define("users", {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW,
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW,
},
});
}
現在只是為了播放箭頭讓我們創建 another-model.ts
`./src/models/another-model.ts`
import { BuildOptions, DataTypes, Model, Sequelize } from "sequelize";
export interface SkillsAttributes {
id: number;
skill: string;
createdAt?: Date;
updatedAt?: Date;
}
export interface SkillsModel extends Model<SkillsAttributes>, SkillsAttributes {}
export class Skills extends Model<SkillsModel, SkillsAttributes> {}
export type SkillsStatic = typeof Model & {
new (values?: object, options?: BuildOptions): SkillsModel;
};
export function SkillsFactory (sequelize: Sequelize): SkillsStatic {
return <SkillsStatic>sequelize.define("skills", {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
skill: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW,
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW,
},
});
}
我們的實體完成了。 現在數據庫連接。
打開./src/models/index.ts
那里我們將放置 seqelize 實例
`./src/models/index.ts`
import * as sequelize from "sequelize";
import {userFactory} from "./user-model";
import {skillsFactory} from "./other-model";
export const dbConfig = new sequelize.Sequelize(
(process.env.DB_NAME = "db-name"),
(process.env.DB_USER = "db-user"),
(process.env.DB_PASSWORD = "db-password"),
{
port: Number(process.env.DB_PORT) || 54320,
host: process.env.DB_HOST || "localhost",
dialect: "postgres",
pool: {
min: 0,
max: 5,
acquire: 30000,
idle: 10000,
},
}
);
// SOMETHING VERY IMPORTANT them Factory functions expect a
// sequelize instance as parameter give them `dbConfig`
export const User = userFactory(dbConfig);
export const Skills = skillsFactory(dbConfig);
// Users have skills then lets create that relationship
User.hasMay(Skills);
// or instead of that, maybe many users have many skills
Skills.belongsToMany(Users, { through: "users_have_skills" });
// the skill is the limit!
在我們的 index.ts 添加,如果你只是想打開連接
db.sequelize
.authenticate()
.then(() => logger.info("connected to db"))
.catch(() => {
throw "error";
});
或者如果你想創建它們表
db.sequelize
.sync()
.then(() => logger.info("connected to db"))
.catch(() => {
throw "error";
});
有些像這樣
import * as bodyParser from "body-parser";
import * as express from "express";
import { dbConfig } from "./models";
import { routes } from "./routes";
import { logger } from "./utils/logger";
import { timeMiddleware } from "./utils/middlewares";
export function expressApp () {
dbConfig
.authenticate()
.then(() => logger.info("connected to db"))
.catch(() => {
throw "error";
});
const app: Application = express();
if (process.env.NODE_ENV === "production") {
app.use(require("helmet")());
app.use(require("compression")());
} else {
app.use(require("cors")());
}
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true, limit: "5m" }));
app.use(timeMiddleware);
app.use("/", routes(db));
return app;
}
再一次,天空是極限。 如果您這樣做,您將擁有自動完成功能的所有功能。 這里有一個例子: https : //github.com/EnetoJara/resume-app
使用續集打字稿。 將您的表和視圖轉換為擴展 Model 對象的類。
使用類中的注釋來定義您的表。
import {Table, Column, Model, HasMany} from 'sequelize-typescript'; @Table class Person extends Model<Person> { @Column name: string; @Column birthday: Date; @HasMany(() => Hobby) hobbies: Hobby[]; }
通過創建對象創建到 DB 的連接:
const sequelize = new Sequelize(configuration...).
然后將您的表注冊到此對象。
sequelize.add([Person])
如需進一步參考,請檢查此模塊。 續集打字稿
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.