如何使用 TypeScript 和 Sequelize

     2023-03-07     207

关键词:

【中文标题】如何使用 TypeScript 和 Sequelize【英文标题】:How to use TypeScript with Sequelize 【发布时间】:2020-05-17 18:31:05 【问题描述】:

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

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

【问题讨论】:

嘿,这是我找到的最好的解决方案:rousseau-alexandre.fr/en/programming/2019/06/19/… 希望对您有所帮助 【参考方案1】:

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

我们只需要关注文档: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,
        ,
    );


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

open ./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

【讨论】:

创作作品如何实现?当我做 MyModel.create () 他期望一个对象但不完全是模型的属性 你好,como estas ?你可以看看这篇中号帖子medium.com/@enetoOlveda/… 许多 TypeScript 特性不是 ECMAScript 标准的一部分,这并不意味着它们应该被避免。装饰器绝对不是遗留物,它们是 tc39 第 2 阶段的提案,尚未最终确定。 无论你的船是什么 兼容typescript的模型是否可以从sequelize-cli构建?就像我们喜欢sequelize-cli model:generate command?【参考方案2】:

使用 sequelize-typescript。将您的表和视图转换为扩展模型对象的类。

在类中使用注释来定义您的表格。

import Table, Column, Model, HasMany from 'sequelize-typescript';
 
@Table
class Person extends Model<Person> 
 
  @Column
  name: string;
 
  @Column
  birthday: Date;
 
  @HasMany(() => Hobby)
  hobbies: Hobby[];

通过创建对象来创建与数据库的连接:

const sequelize = new Sequelize(configuration...). 

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

sequelize.add([Person])

如需进一步参考,请查看此模块。 Sequelize-Typescript

【讨论】:

JSPM + TypeScript + PhotoSwipe:如何成功导入和使用库?

】JSPM+TypeScript+PhotoSwipe:如何成功导入和使用库?【英文标题】:JSPM+TypeScript+PhotoSwipe:Howtosuccessfullyimportandusethelibrary?【发布时间】:2016-07-0919:34:48【问题描述】:我正在尝试在我的JSPM和TypeScript项目中使用PhotoSwipe库但没有成功(... 查看详情

如何使用 nodejs 和 typescript 自动重启节点应用程序?

】如何使用nodejs和typescript自动重启节点应用程序?【英文标题】:Howtoautomaticrestartnodeapplicationwithnodejsandtypescript?【发布时间】:2021-08-2814:54:07【问题描述】:我正在使用nodejs、express、typescript和babel建立一个新项目。所以我使用b... 查看详情

Storybook 和 AntDesign 组件 - 如何使用 CRA 和 Typescript 进行设置?

】Storybook和AntDesign组件-如何使用CRA和Typescript进行设置?【英文标题】:StorybookandAntDesigncomponents-howtoset-upwithCRA&Typescript?【发布时间】:2020-02-2712:58:30【问题描述】:我想在我的CRA项目中使用Typescript使用构建在AntDesign组件之上... 查看详情

MUI 和 TypeScript:如何使用 !important?

】MUI和TypeScript:如何使用!important?【英文标题】:MUIandTypeScript:Howtouse!important?【发布时间】:2019-04-0815:10:42【问题描述】:我正在构建一个React应用程序,并且我正在为我的组件使用MUI。我想知道如何将!important属性赋予样式?... 查看详情

如何使用 npm 链接和使用 TypeScript 编写的模块进行开发?

】如何使用npm链接和使用TypeScript编写的模块进行开发?【英文标题】:HowtousenpmlinkwithamodulewrittenusingTypeScriptfordevelopment?【发布时间】:2020-02-1603:25:15【问题描述】:我正在使用TypeScript和Webpack构建一个库。为了开发这个库,我创... 查看详情

如何使用 Node 和 TypeScript 获取异步堆栈跟踪?

】如何使用Node和TypeScript获取异步堆栈跟踪?【英文标题】:HowcanIgetasyncstacktraceswithNodeandTypeScript?【发布时间】:2019-11-0520:14:33【问题描述】:我希望我可以让堆栈跟踪在TypeScript中工作。我似乎只看到最底部的函数名称。我在Win... 查看详情

出现错误:如何正确使用来自 typescript 的转译和键入的 typescript npm 模块?

】出现错误:如何正确使用来自typescript的转译和键入的typescriptnpm模块?【英文标题】:Gettingerrors:HowcanIproperlyconsumemytranspiledandtypedtypescriptnpmmodulefromtypescript?【发布时间】:2016-11-2208:11:29【问题描述】:我是still正在尝试打字稿... 查看详情

如何使用 usestate 和 setstate 而不是 this.setState 使用 react 和 typescript?

】如何使用usestate和setstate而不是this.setState使用react和typescript?【英文标题】:Howtouseusestateandsetstateinsteadofthis.setStateusingreactandtypescript?【发布时间】:2020-09-1618:38:06【问题描述】:我想使用react和typescript实现一个DragAndDrop组件,... 查看详情

如何使用 Preact 和 TypeScript 对子组件进行类型检查?

】如何使用Preact和TypeScript对子组件进行类型检查?【英文标题】:HowtotypecheckcomponentchildrenwithPreactandTypeScript?【发布时间】:2019-01-1906:35:41【问题描述】:是否可以使用TypeScript(v3.0.1)和Preact(v8.3.1)对子组件进行类型检查?在React中... 查看详情

如何在 NodeJS、Mongoose 和 TypeScript 中使用日期和时间?

】如何在NodeJS、Mongoose和TypeScript中使用日期和时间?【英文标题】:HowtoworkwithDateandTimeinNodeJS,MongooseandTypeScript?【发布时间】:2019-05-2306:02:17【问题描述】:我来自java世界,我从NodeJS开始。我很难理解如何在NodeJS中处理日期和时... 查看详情

如何使用 NodeJS 13 和 Typescript 3.8 导入 esm 模块?

】如何使用NodeJS13和Typescript3.8导入esm模块?【英文标题】:HowtoimportesmmoduleswithNodeJS13,andTypescript3.8?【发布时间】:2020-08-1320:36:10【问题描述】:我在NodeJS中的一些导入有问题。我想使用Typescript3.8的新功能,比如私有字段:#myPriva... 查看详情

如何在 Typescript 中使用 Webpack 'require' 和 'require.ensure'

】如何在Typescript中使用Webpack\\\'require\\\'和\\\'require.ensure\\\'【英文标题】:HowtouseWebpacks\'require\'and\'require.ensure\'inTypesScript如何在Typescript中使用Webpack\'require\'和\'require.ensure\'【发布时间】:2017-05-2715:51:15【问题描述】:我正在尝... 查看详情

如何使用 Axios 和 Typescript 等待响应?

】如何使用Axios和Typescript等待响应?【英文标题】:HowcanIwaitforaresponseusingAxiosandTypescript?【发布时间】:2019-12-0909:55:35【问题描述】:我需要您的帮助来调整我的方法以等待axios响应。基本上,我向WebService发送请求,我需要等待... 查看详情

如何使用 Mongoose 和 Typescript 实现强类型静态模式函数?

】如何使用Mongoose和Typescript实现强类型静态模式函数?【英文标题】:HowtoachievestronglytypedstaticschemafunctionsusingMongoosewithTypescript?【发布时间】:2019-11-2617:17:11【问题描述】:我想知道在使用TypeScript时,为MongooseSchemas实现强类型静... 查看详情

如何使用 redux-thunk 和 TypeScript 调度 ThunkAction

】如何使用redux-thunk和TypeScript调度ThunkAction【英文标题】:HowtodispatchThunkActionwithredux-thunkandTypeScript【发布时间】:2021-02-2715:25:45【问题描述】:我在使用Typescript调度redux-thunk操作时遇到问题。importAnyAction,applyMiddleware,createStorefrom\... 查看详情

如何使用 Aurelia 和 typescript 获得业力覆盖?

】如何使用Aurelia和typescript获得业力覆盖?【英文标题】:Howtogetkarma-coverageworkingwithAureliaandtypescript?【发布时间】:2017-07-3012:49:35【问题描述】:我们的网站正在使用Aurelia导航骨架打字稿入门套件。我能够让单元测试与jasmine和ka... 查看详情

如何防止 jquery 使用 webpack 和 typescript 导入两次?

】如何防止jquery使用webpack和typescript导入两次?【英文标题】:Howtopreventjqueryfromimportingtwicewithwebpack&typescript?【发布时间】:2018-05-1707:03:36【问题描述】:我收到了这个错误UncaughtTypeError:$(...).dialogisnotafunction原因似乎是因为我... 查看详情

如何生产和使用 Typescript 编写的多模块 NPM 包

】如何生产和使用Typescript编写的多模块NPM包【英文标题】:Howtoproduceandconsumemulti-moduleNPMpackageswritteninTypescript【发布时间】:2018-10-1302:15:21【问题描述】:很长一段时间以来,我一直非常习惯使用Typescript创建和使用NPM包,但这些... 查看详情