【问题标题】:Use ENUM with Sequelize and Typescript将 ENUM 与 Sequelize 和 Typescript 一起使用
【发布时间】:2020-04-17 17:49:28
【问题描述】:

我正在尝试创建一个带有 USER 类的 API,该类可以有不止一种使用 API 进行身份验证的方式。

我已经设法让它与只有 1 个凭据的 1 个用户一起工作,但是当尝试扩展以允许多个凭据时,我得到了错误: UnhandledPromiseRejectionWarning: SequelizeDatabaseError: (conn=498, no: 1265, SQLState: 01000) Data truncated for column 'type' at row 1

我目前拥有的是这样的:

User.hasMany(Credential, { foreignKey: 'id', sourceKey: 'id' });

还有这个:

//Credential.ts
export function CredentialInit(sequelize: Sequelize) {
    let cred = Object.keys(CredentialType);
    let credArr: string[] = [];
    for(let i = 0; i < cred.length/2; i++) {
        credArr.push(`${i}`);
    };
    Credential.init({
        email: {
            type: DataTypes.STRING,
            allowNull: true
        },
        password: {
            type: DataTypes.STRING,
            allowNull: true
        },
        token: {
            type: DataTypes.STRING,
            allowNull: true
        },
        type: {
            type: DataTypes.ENUM,
            values: credArr,
            allowNull: false
        }
    }, {
        sequelize: sequelize,
        tableName: 'credentials'
    });
}

export enum CredentialType {
    EMAIL,
    TOKEN
}

export class Credential extends BaseModel {
    public type!: CredentialType;
    public token?: string;
    public email?: string;
    public password?: string;
}

还有这个模型可以从我的所有其他模型中删除这些东西。

//BaseModel.ts
export class BaseModel extends Model {
    public id?: number;
    public readonly createdAt?: Date;
    public readonly updatedAt?: Date;
}

知道为什么我会收到此消息吗? 我这样写是因为我不想两次声明枚举的内容。如果改变了,我希望它在任何地方都改变....

【问题讨论】:

  • 为什么只循环了 ~ 一半的枚举键?
  • 前半部分是元素的索引,或者赋值('0','1'),后半部分是元素的字符串表示形式('EMAIL', 'TOKEN')
  • 现在意识到我可以完成 Object.keys(CredentialType).slice(0,Object.keys(CredentialType)/2) 并跳过 for 循环......无论如何...... XD跨度>

标签: node.js typescript enums sequelize.js


【解决方案1】:

好的,经过更多的试验,我找到了一种方法。 由于枚举选项在 typescript/javascript 中表示为数字,因此我更改了与枚举对应的数据库类型:

Credential.init({
    email: {
        type: DataTypes.STRING,
        allowNull: true
    },
    password: {
        type: DataTypes.STRING,
        allowNull: true
    },
    token: {
        type: DataTypes.STRING,
        allowNull: true
    },
    type: {
        type: DataTypes.INTEGER,
        allowNull: false
    }
}, {
    sequelize: sequelize,
    tableName: 'credentials'
});

当它以整数形式保存到数据库时,错误就消失了。

【讨论】:

  • 或者你可以用字符串代替数字export enum CredentialType { EMAIL = "EMAIL", TOKEN = "TOKEN" }
猜你喜欢
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
  • 2017-08-23
  • 2015-11-09
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
  • 2017-02-21
相关资源
最近更新 更多