如何使用 TypeScript 和 Sequelize [英] How to use TypeScript with Sequelize

查看:12
本文介绍了如何使用 TypeScript 和 Sequelize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I already have my server application written in Node, PostgreSQL, Sequelize using Fastify.

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

Now I would like to use TypeScript. Can anyone tell me how to begin rewriting my Server application using TypeScript.

推荐答案

你应该尽量避免使用装饰器,它们不是 ECMAScript 标准.他们甚至被认为是遗产.这就是为什么我要向你展示如何将 sequelize 与 typescript 一起使用.

Using Decorators is something you should avoid as much as possible, they are not ECMAScript standard. They are even consider legacy. It is why I'm going to show you how to use sequelize with typescript.

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

we just need to follow the docs: https://sequelize.org/v5/manual/typescript.html but as it is not very clear, or at least to me. It took me a while understand it.

上面说你需要安装这棵树的东西

There it says that you need to install this tree things

 * @types/node
 * @types/validator // this one is not need it
 * @types/bluebird

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

然后让我们假设您的项目如下所示:

then let's assume your project looks like so:

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

Now just to play arrow let's create 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,
        },
    });
}

我们的实体已经完成.现在是数据库连接.

Our Entities are done. now the db connection.

打开 ./src/models/index.ts 我们要放置 seqelize 实例的地方

open ./src/models/index.ts there is where we gonna place the seqelize instance

`./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 上添加,如果你只是想打开连接

on our index.ts add, if you just want to open connection

  db.sequelize
        .authenticate()
        .then(() => logger.info("connected to db"))
        .catch(() => {
            throw "error";
        });

或者如果你想创建他们的表

or if you want to create them tables

  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

Once again the sky is the limit. If you do this you'll have all the power of the autocomplete. here an example: https://github.com/EnetoJara/resume-app

这篇关于如何使用 TypeScript 和 Sequelize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆