typescript - 在 NestJs 插件设计中附加 Sequelize 模型字段
问题描述
我正在尝试使用带有动态模块和EventEmitter的 NestJS 开发插件设计逻辑
目的是使用多个彼此不知道的插件来扩展核心逻辑。
找到了一个不错的插件加载器。
想法似乎对我有用,直到我遇到从核心模块发出 Sequalize 模型实例的问题。确切的问题是 Sequalize 已经加载了不知道其他字段的特定插件模块实例,除非我创建新实例并再次从数据库重新加载数据,否则我不能在其他插件逻辑中使用它们。
Structure:
- core
- models
* Customer (fields: {id, name})
- plugins
- pluginA (dependent on core)
- models
* Customer extends core/models/Customer (fields: {address})
- pluginB (dependent on core)
- models
* Customer extends core/models/Customer (fields: {age})
我的愿景是能够在应用程序引导上合并所有 3 个客户模型,然后将其添加到 Sequalize。
我曾尝试使用Mixins,但它只会合并类函数而不是属性。离开示例脚本
import { Sequelize, Model, Table, Column, DataType } from 'sequelize-typescript';
/** From Core Module */
@Table({
tableName: 'customer',
freezeTableName: true,
timestamps: false,
})
class CustomerCore extends Model {
@Column({ type: DataType.INTEGER, primaryKey: true })
id: number;
@Column({ type: DataType.TEXT })
name: string | null;
}
/** From PluginA */
@Table({
tableName: 'customer',
freezeTableName: true,
timestamps: false,
})
class CustomerA extends CustomerCore {
@Column({ type: DataType.TEXT, allowNull: true })
address?: string;
}
/** From PluginB */
@Table({
tableName: 'customer',
freezeTableName: true,
timestamps: false,
})
class CustomerB extends CustomerCore {
@Column({ type: DataType.INTEGER, allowNull: true })
age?: number;
}
/**
* Mixins example which wont work
* */
function applyMixins(derivedCtor: any, constructors: any[]) {
constructors.forEach((baseCtor) => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
Object.defineProperty(
derivedCtor.prototype,
name,
Object.getOwnPropertyDescriptor(baseCtor.prototype, name) ||
Object.create(null)
);
});
});
}
class Customer extends CustomerCore {}
interface Customer extends CustomerCore, CustomerA, CustomerB {};
applyMixins(Customer, [CustomerCore, CustomerA, CustomerB])
const sequelize = new Sequelize({
host: '127.0.0.1',
dialect: 'postgres',
username: 'postgres',
password: 'password',
database: 'test',
});
/** Get error: cannot read property 'length' of undefined */
sequelize.addModels([Customer]);
有人知道如何解决这个问题吗?
先感谢您。
解决方案
推荐阅读
- c# - 写入流,然后创建一个新流
- video - DE-10 FFMPEG Raw YCbCr 4:2:2 Frame to PNG or Video 导致不良结果
- canvas - 画布上圆形图像上的外阴影?
- typescript - Sveltekit - 从 lib 访问会话
- mysql - PHP Sql 使选择语句不区分大小写
- kubernetes - 如何通过 Ingress 公开 Linkerd 仪表板
- google-cloud-platform - 在不使用 Google 的 SDK 的情况下访问 Google CloudTasks API
- javascript - 反应过滤嵌套键结果未定义,异步
- javascript - 如何定期访问在另一个文件中不断更新的变量?
- julia - Julia 标记宽度或重量