node.js - 将 ENUM 与 Sequelize 和 Typescript 结合使用

标签 node.js typescript enums sequelize.js

我正在尝试创建一个带有 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;
}

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

最佳答案

好吧,经过更多的实验,我找到了一种方法。
由于枚举选项在 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'
});

当它作为整数保存到数据库时,错误就消失了。

关于node.js - 将 ENUM 与 Sequelize 和 Typescript 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59506149/

相关文章:

Node.js MongoDB 驱动游标计数不正确

javascript - GraphQL - 将非特定对象的对象作为参数传递

javascript - 如何获取动态生成元素的id属性?

typescript - Google Pay TypeScript 定义

mysql - MySQL 中的 Like 子句未按预期显示输出

javascript - NodeJS 生成器永远不会到达某一行?

node.js - TravisCI 在 Node BCrypt 上失败并出现 node-gyp 错误

sql-server - 元素隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引类型 'Type'

json - 尝试反序列化 json 中的枚举时索引值超出合法索引范围

mysql - 插入附加到 ENUM 之前的 SQL 触发器