首页 > 解决方案 > 在 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]);

有人知道如何解决这个问题吗?

先感谢您。

标签: typescriptpluginssequelize.jsnestjssequelize-typescript

解决方案


推荐阅读