如何在 Sequelize 中使用 TypeScript

Raf*_*ael 13 postgresql node.js sequelize.js typescript fastify

我已经使用 Fastify 用 Node、PostgreSQL、Sequelize 编写了我的服务器应用程序。

现在我想使用 TypeScript。谁能告诉我如何开始使用 TypeScript 重写我的服务器应用程序。

Ern*_*sto 25

使用装饰器是你应该尽可能避免的事情,它们不是 ECMAScript 标准。他们甚至被视为遗产。这就是为什么我要向您展示如何在打字稿中使用 sequelize。

我们只需要遵循文档:https : //sequelize.org/v5/manual/typescript.html但因为它不是很清楚,或者至少对我来说。我花了一段时间才明白。

那里说你需要安装这棵树的东西

 * @types/node
 * @types/validator // this one is not need it
 * @types/bluebird
Run Code Online (Sandbox Code Playgroud)

npm i -D @types/node @types/bluebird

那么让我们假设您的项目如下所示:

myProject
--src
----models
------index.ts
------user-model.ts
------other-model.ts
----controllers
----index.ts
--package.json
Run Code Online (Sandbox Code Playgroud)

让我们先创建用户模型

 * @types/node
 * @types/validator // this one is not need it
 * @types/bluebird
Run Code Online (Sandbox Code Playgroud)

现在只是为了播放箭头让我们创建 another-model.ts

myProject
--src
----models
------index.ts
------user-model.ts
------other-model.ts
----controllers
----index.ts
--package.json
Run Code Online (Sandbox Code Playgroud)

我们的实体完成了。现在数据库连接。

打开./src/models/index.ts那里我们将放置 seqelize 实例

`./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,
        },
    });
}
Run Code Online (Sandbox Code Playgroud)

在我们的 index.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,
        },
    });
}

Run Code Online (Sandbox Code Playgroud)

或者如果你想创建它们表

  db.sequelize
        .sync()
        .then(() => logger.info("connected to db"))
        .catch(() => {
            throw "error";
        });
Run Code Online (Sandbox Code Playgroud)

有些像这样

`./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!

Run Code Online (Sandbox Code Playgroud)

再一次,天空是极限。如果您这样做,您将拥有自动完成功能的所有功能。这里有一个例子:https : //github.com/EnetoJara/resume-app

  • 许多 TypeScript 功能并不是 ECMAScript 标准的一部分,这并不意味着应该避免使用它们。装饰器绝对不是遗产,它们是尚未最终确定的 tc39 第 2 阶段提案。 (3认同)

Tah*_*med 8

使用续集打字稿。将您的表和视图转换为扩展 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[];
}
Run Code Online (Sandbox Code Playgroud)

通过创建对象创建到 DB 的连接:

const sequelize = new Sequelize(configuration...). 
Run Code Online (Sandbox Code Playgroud)

然后将您的表注册到此对象。

sequelize.add([Person])
Run Code Online (Sandbox Code Playgroud)

如需进一步参考,请检查此模块。 续集打字稿