LoopBack 3 到 LoopBack 4 模型 Mixin 迁移实战指南

原创2026-10-13 19:00:541,940 阅读
文章标签:后端微服务

LoopBack 3 到 LoopBack 4 模型 Mixin 迁移实战指南

导读

本文基于 LoopBack 官方迁移指南,系统讲解如何把 LoopBack 3(LB3)中的模型属性 Mixin(property mixin)与自定义模型方法 / 远程方法 Mixin(custom method / remote method mixin)迁移到 LoopBack 4(LB4)。LoopBack 4 将 LB3 中一个模型类承担的三重职责拆分为 Model(描述数据结构)、Repository(数据访问 API)、Controller(REST API)三个独立类,mixin 也相应地从"向模型注入属性和方法"演进为"通过类工厂函数(class factory function)向模型、仓库、控制器注入能力"。读完本文,你将掌握 LB4 中定义与使用 mixin 的完整套路,并能把 LB3 的 mixin 代码逐行改写成等价的 LB4 TypeScript 实现。

引言:迁移背景与架构变化

在 LoopBack 3 中,向模型添加属性 Mixin 和方法 Mixin 非常容易:把 mixin 逻辑放进 mixins 目录、在 server/model-config.json 中登记目录位置、在模型 JSON 中声明 mixin 名称。到了 LoopBack 4,由于模型、仓库、控制器三种职责的解耦(详见 Migrating custom model methods),mixin 的迁移也变得同样简单——只需使用 mixin 类工厂函数。

所谓类工厂函数,就是"接收一个基类、返回一个继承自该基类并混入新成员的新类"的函数。在 LoopBack 4 中,模型、仓库、控制器乃至应用类(Application)都可以通过这种方式扩展。本文以两个典型场景为主线:一是给模型添加 category 属性,二是给模型添加 findByTitle 自定义方法并暴露为新端点。

创建属性 Mixin(Property Mixin)

本节对比 LB3 与 LB4 如何通过 mixin 给模型添加属性。

LoopBack 3 的做法

LB3 中创建模型属性 Mixin 需要三步:

  1. 在 mixins 目录中放置 mixin 逻辑文件;
  2. 在 server/model-config.json 中登记 mixin 目录位置;
  3. 在模型的 JSON 文件中加入 mixin 名称与布尔值开关。

下面以给模型添加一个 category 属性为例。

定义模型属性 Mixin:common/mixins/category.js

common/mixins/category.js 会给任意模型添加一个必填的 category 属性:

module.exports = function (Model, options) {
  Model.defineProperty('category', {type: 'string', required: true});
};

更新 model-config.json

server/model-config.json 需要包含:所有 models 的路径、所有 mixins 的路径,以及接收 mixin 内容的模型条目(本例为 Note):

{
  "_meta": {
    "sources": [
      "loopback/common/models",
      "loopback/server/models",
      "../common/models",
      "./models"
    ],
    "mixins": [
      "loopback/common/mixins",
      "loopback/server/mixins",
      "../common/mixins",
      "./mixins"
    ]
  },

 // ... other entries

  "Note": {
    "dataSource": "db"
  }
}

将 category.js Mixin 应用到模型

要扩展 Note 模型,需在 common/models/note.json 中添加 mixins 段,声明需要应用哪些 mixin:

{
  "name": "Note",
  "properties": {
    "title": {
      "type": "string",
      "required": true
    },
    "content": {
      "type": "string"
    }
  },
  "mixins": {
    "Category": true
  }
}

Category 的值为 true 时应用 category.js 属性 mixin;为 false 时不应用。

LoopBack 4 的做法

LB4 中创建模型属性 Mixin 需要四步:

  1. 创建继承 Entity 的基模型类;
  2. 将 mixin 类工厂函数放在独立文件中;
  3. 照常使用 CLI 生成模型;
  4. 调整模型文件以使用 mixin 类工厂函数。

定义继承 Entity 的 BaseEntity 类

在 src/models/base-entity.ts 中定义基模型类 BaseEntity,它将作为 mixin 的输入基类:

import {Entity} from '@loopback/repository';
export class BaseEntity extends Entity {}

这一步是必要的,因为仓库源码中 Entity 类的抽象基类 Model 的构造签名需要 Entity 具备可继承性(见 Entity 与 Model 类定义),而直接让 mixin 去继承一个带有装饰器元数据的复杂类在 TypeScript 下会有诸多限制,先垫一层薄基类可以简化类型推导。

定义模型属性 Mixin 类工厂函数

src/mixins/category-property-mixin.ts 中的 AddCategoryPropertyMixin 类工厂函数会给任意模型添加必填属性 category:

import {MixinTarget} from '@loopback/core';
import {property, Model} from '@loopback/repository';

/**
 * A mixin factory to add `category` property
 *
 * @param superClass - Base Class
 * @typeParam T - Model class
 */
export function AddCategoryPropertyMixin<T extends MixinTarget<Model>>(
  superClass: T,
) {
  class MixedModel extends superClass {
    @property({
      type: 'string',
      required: true,
    })
    category: string;
  }
  return MixedModel;
}

注意:目前 TypeScript 不允许在类表达式中使用装饰器,因此必须给类一个具名声明,再将其返回。

关于 @property 装饰器:它在底层通过 PropertyDecoratorFactory.createDecorator 把属性定义注册到 MODEL_PROPERTIES_KEY 元数据键上(见 @property 装饰器实现),随后 @model() 在构建模型定义时会收集这些元数据,因此 mixin 中新声明的属性会与模型类自身声明的属性一起进入模型定义(definition),从而参与序列化、校验与持久化。

通过 CLI 生成模型

一个名为 Note、含 id、title、content 三个属性的 CLI 生成模型如下:

import {Entity, model, property} from '@loopback/repository';

@model()
export class Note extends Entity {
  @property({
    type: 'number',
    id: true,
    generated: true,
  })
  id?: number;

  @property({
    type: 'string',
    required: true,
  })
  title: string;

  @property({
    type: 'string',
  })
  content?: string;

  constructor(data?: Partial<Note>) {
    super(data);
  }
}

export interface NoteRelations {
  // describe navigational properties here
}

export type NoteWithRelations = Note & NoteRelations;

调整模型文件以使用 AddCategoryPropertyMixin

模型文件只需三处调整:

  • 导入 BaseEntity 类;
  • 导入 AddCategoryPropertyMixin mixin;
  • 将 Note 的类声明改为继承 mixin 函数返回的类,并以 BaseEntity 作为传入的父类。
import {model, property} from '@loopback/repository';
import {AddCategoryPropertyMixin} from '../mixins/category-property-mixin';
import {BaseEntity} from './base-entity';

@model()
export class Note extends AddCategoryPropertyMixin(BaseEntity) {
  @property({
    type: 'number',
    id: true,
    generated: true,
  })
  id?: number;

  @property({
    type: 'string',
    required: true,
  })
  title: string;

  @property({
    type: 'string',
  })
  content?: string;

  constructor(data?: Partial<Note>) {
    super(data);
  }
}

export interface NoteRelations {
  // describe navigational properties here
}

export type NoteWithRelations = Note & NoteRelations;

至此,必填属性 category 已通过 mixin 类工厂函数添加到 Note 模型中。

创建自定义模型方法与远程方法 Mixin

本节对比 LB3 与 LB4 如何通过 mixin 给模型添加自定义方法 / 远程方法,并使其暴露为新端点。findByTitle 的完整非 mixin 实现方式参见 Migrating custom model methods 中的 "Add a New Model Method And a New Endpoint" 一节。

LoopBack 3 的做法

LB3 中创建自定义模型方法 / 远程方法 Mixin 的步骤与属性 Mixin 一致(放置逻辑文件、登记目录、在模型 JSON 中声明),区别在于 mixin 值可以是一个选项对象而不仅是布尔值。

定义模型方法 Mixin:common/mixins/findByTitle.js

common/mixins/findByTitle.js 给任意模型添加 findByTitle 自定义方法,并注册路径为 /findByTitle 的远程方法。选项属性 returnArgumentName 可定制返回参数名,未指定时默认使用 items:

module.exports = function (Model, options) {
  const returnArgumentName = options.returnArgumentName
    ? options.returnArgumentName
    : 'items';

  Model.remoteMethod('findByTitle', {
    http: {
      path: '/findByTitle',
      verb: 'get',
    },
    accepts: {arg: 'title', type: 'string'},
    returns: {arg: returnArgumentName, type: [Model], root: true},
  });

  Model.findByTitle = function (title, cb) {
    var titleFilter = {
      where: {
        title: title,
      },
    };
    Model.find(titleFilter, cb);
  };
};

对于名为 Note 的模型,这会暴露端点 /Notes/findByTitle。同时确保 model-config.json 已按 更新 model-config.json 一节正确配置。

将 findByTitle.js Mixin 应用到模型

在 common/models/note.json 中添加 mixins 段:

{
  "name": "Note",
  "properties": {
    "title": {
      "type": "string",
      "required": true
    },
    "content": {
      "type": "string"
    }
  },

  "mixins": {
    "FindByTitle": {
      "returnArgumentName": "notes"
    },

    "Category": true
  }
}

为 FindByTitle 指定选项对象与指定 true 等价,都会应用 findByTitle.js mixin;值为 false 则不应用。同一模型可同时叠加多个 mixin(如 Category 与 FindByTitle)。

LoopBack 4 的做法

LB4 中,findByTitle 的数据访问逻辑落在 NoteRepository 上,REST 端点逻辑落在 NoteController 上,因此需要定义两个 mixin(仓库 mixin 与控制器 mixin)分别注入两者,步骤为:

  1. 为 findByTitle 方法定义公共接口;
  2. 将两个 mixin 类工厂函数放在独立文件中;
  3. 照常使用 CLI 生成仓库与控制器;
  4. 调整仓库与控制器文件以使用各自的 mixin 类工厂函数。

定义 findByTitle 方法的公共接口

在 src/mixins/find-by-title-interface.ts 中定义公共接口 FindByTitle:

import {Model} from '@loopback/repository';

/**
 * An interface to allow finding notes by title
 */
export interface FindByTitle<M extends Model> {
  findByTitle(title: string): Promise<M[]>;
}

定义仓库 Mixin 类工厂函数

src/mixins/find-by-title-repository-mixin.ts 中的 FindByTitleRepositoryMixin 给任意仓库添加 findByTitle 方法:

import {MixinTarget} from '@loopback/core';
import {Model, CrudRepository, Where} from '@loopback/repository';
import {FindByTitle} from './find-by-title-interface';

/*
 * This function adds a new method 'findByTitle' to a repository class
 * where 'M' is a model which extends Model
 *
 * @param superClass - Base class
 *
 * @typeParam M - Model class which extends Model
 * @typeParam R - Repository class
 */
export function FindByTitleRepositoryMixin<
  M extends Model & {title: string},
  R extends MixinTarget<CrudRepository<M>>,
>(superClass: R) {
  class MixedRepository extends superClass implements FindByTitle<M> {
    async findByTitle(title: string): Promise<M[]> {
      const where = {title} as Where<M>;
      const titleFilter = {where};
      return this.find(titleFilter);
    }
  }
  return MixedRepository;
}

注意两个泛型约束:M extends Model & {title: string} 要求被查询的模型具备 title 属性;R extends MixinTarget<CrudRepository<M>> 要求基类必须是一个可构造的 CRUD 仓库类,从而保证 this.find(...) 可用。

通过 CLI 生成仓库

模型 Note 的 CLI 生成仓库如下:

export class NoteRepository extends DefaultCrudRepository<
  Note,
  typeof Note.prototype.id,
  NoteRelations
> {
  constructor(@inject('datasources.db') dataSource: DbDataSource) {
    super(Note, dataSource);
  }
}

调整 NoteRepository 使用 FindByTitleRepositoryMixin

仓库文件只需两处调整:导入 mixin 类工厂函数;将 NoteRepository 的声明改为继承 mixin 函数返回的类,并以 DefaultCrudRepository 作为传入父类:

import {FindByTitleRepositoryMixin} from '../mixins/find-by-title-repository-mixin';
import {DefaultCrudRepository} from '@loopback/repository';
import {Note, NoteRelations} from '../models';
import {DbDataSource} from '../datasources';
import {inject, Constructor} from '@loopback/core';

/**
 * A repository for `Note` with `findByTitle`
 */
export class NoteRepository extends FindByTitleRepositoryMixin<
  Note,
  Constructor<
    DefaultCrudRepository<Note, typeof Note.prototype.id, NoteRelations>
  >
>(DefaultCrudRepository) {
  constructor(@inject('datasources.db') dataSource: DbDataSource) {
    super(Note, dataSource);
  }
}

注意:泛型第二参数需要传入 Constructor<DefaultCrudRepository<...>> 类型,因为 DefaultCrudRepository 是泛型类,直接写类名无法满足 MixinTarget 的构造签名约束。至此 findByTitle 方法已通过 mixin 类工厂函数注入仓库。

定义控制器 Mixin 类工厂函数

src/mixins/find-by-title-controller-mixin.ts 中的 FindByTitleControllerMixin 给任意控制器添加 findByTitle 方法并暴露 GET 端点:

import {MixinTarget} from '@loopback/core';
import {Model} from '@loopback/repository';
import {FindByTitle} from './find-by-title-interface';
import {param, get, getModelSchemaRef} from '@loopback/rest';

/**
 * Options to mix in findByTitle
 */
export interface FindByTitleControllerMixinOptions {
  /**
   * Base path for the controller
   */
  basePath: string;
  /**
   * Model class for CRUD
   */
  modelClass: typeof Model;
}

/**
 * A mixin factory for controllers to be extended by `FindByTitle`
 * @param superClass - Base class
 * @param options - Options for the controller
 *
 * @typeParam M - Model class
 * @typeParam T - Base class
 */
export function FindByTitleControllerMixin<
  M extends Model,
  T extends MixinTarget<object>,
>(superClass: T, options: FindByTitleControllerMixinOptions) {
  class MixedController extends superClass implements FindByTitle<M> {
    // Value will be provided by the subclassed controller class
    repository: FindByTitle<M>;

    @get(`${options.basePath}/findByTitle/{title}`, {
      responses: {
        '200': {
          description: `Array of ${options.modelClass.modelName} model instances`,
          content: {
            'application/json': {
              schema: {
                type: 'array',
                items: getModelSchemaRef(options.modelClass, {
                  includeRelations: true,
                }),
              },
            },
          },
        },
      },
    })
    async findByTitle(@param.path.string('title') title: string): Promise<M[]> {
      return this.repository.findByTitle(title);
    }
  }

  return MixedController;
}

要定制端点的 OpenAPI 描述,mixin 类工厂函数需要接收选项,因此定义了 FindByTitleControllerMixinOptions 接口(含 basePath 与 modelClass 两个字段)。同时,建议把注入的仓库在控制器父类中统一命名为 this.repository,以便 mixin 类工厂函数以简单一致的名称访问。

通过 CLI 生成控制器

模型 Note 的 CLI 生成控制器如下(为节省篇幅仅展示部分实现;完整示例可参考 TodoController):

export class NoteController {
  constructor(
    @repository(NoteRepository)
    public noteRepository: NoteRepository,
  ) {}

  @post('/notes', {
    responses: {
      '200': {
        description: 'Note model instance',
        content: {'application/json': {schema: getModelSchemaRef(Note)}},
      },
    },
  })
  async create(
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(Note, {
            title: 'NewNote',
            exclude: ['id'],
          }),
        },
      },
    })
    note: Omit<Note, 'id'>,
  ): Promise<Note> {
    return this.noteRepository.create(note);
  }

  // ...
  // remaining CRUD endpoints
  // ...
}

调整 NoteController 使用 FindByTitleControllerMixin

控制器文件需要做六处调整:

  1. 导入 FindByTitleControllerMixinOptions 接口;
  2. 导入 FindByTitleControllerMixin mixin 类工厂函数;
  3. 准备 mixin 的选项;
  4. 将 NoteController 的声明改为继承 mixin 函数返回的类,以 Object 作为传入父类;
  5. 将选项传入 mixin;
  6. 把注入的仓库名从 noteRepository 改为 repository,方便 mixin 类工厂函数访问。
import {Note} from '../models';
import {
  FindByTitleControllerMixin,
  FindByTitleControllerMixinOptions,
} from '../mixins/find-by-title-controller-mixin';
import {Constructor} from '@loopback/core';

import {
  Count,
  CountSchema,
  Filter,
  repository,
  Where,
} from '@loopback/repository';
import {
  post,
  param,
  get,
  getFilterSchemaFor,
  getModelSchemaRef,
  getWhereSchemaFor,
  patch,
  put,
  del,
  requestBody,
} from '@loopback/rest';
import {NoteRepository} from '../repositories';

const options: FindByTitleControllerMixinOptions = {
  basePath: '/notes',
  modelClass: Note,
};

export class NoteController extends FindByTitleControllerMixin<
  Note,
  Constructor<Object>
>(Object, options) {
  constructor(
    @repository(NoteRepository)
    public repository: NoteRepository,
  ) {
    super();
  }

  @post('/notes', {
    responses: {
      '200': {
        description: 'Note model instance',
        content: {'application/json': {schema: getModelSchemaRef(Note)}},
      },
    },
  })
  async create(
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(Note, {
            title: 'NewNote',
            exclude: ['id'],
          }),
        },
      },
    })
    note: Omit<Note, 'id'>,
  ): Promise<Note> {
    return this.repository.create(note);
  }

  // ...
  // remaining CRUD endpoints
  // ...
}

至此 findByTitle 方法已通过 mixin 类工厂函数注入控制器,并暴露端点 /notes/findByTitle/{title}。

深入原理:MixinTarget 与框架内置 Mixin

理解了上述迁移套路后,再深入了解一下支撑这一切的底层类型与框架自身对 mixin 的使用,会让你的自定义 mixin 写得更地道。

MixinTarget:为 mixin 量身定制的构造签名

所有 mixin 类工厂函数的泛型约束都来自 @loopback/core 导出的 MixinTarget 类型(见 mixin-target.ts 定义):

export type MixinTarget<T extends object> = Constructor<{
  // 仅枚举 public 成员,避免 TypeScript 报错:
  //   Property '(name)' of exported class expression
  //   may not be private or protected.ts(4094)
  [P in keyof T]: T[P];
}>;

它取代了 typeof Target 在 mixin 场景下的写法,是 TypeScript 若干限制(见 mixin-target.ts 源码注释)的官方工作区方案,例如:

  • TypeScript 不允许 mixin 访问基类的 protected 成员,可用 @ts-ignore + 类型断言绕过;
  • mixin 不能覆盖来自映射类型的继承方法,也需要 @ts-ignore 抑制错误。

在仓库的单元测试 mixin-target.unit.ts 中,可以验证 MixinTarget 约束下的 mixin 既能访问基类成员,也能贡献新的属性与方法:

function MyMixin<T extends MixinTarget<BaseClass>>(superClass: T) {
  return class extends superClass {
    public mixinProp = 'mixin';
    public mixinMethod() {
      return 'mixin-method';
    }
  };
}
class Extended extends MyMixin(BaseClass) {}
const instance = new Extended();
// instance.baseProp === 'base'
// instance.mixinMethod() === 'mixin-method'

框架内置 Mixin:BootMixin、RepositoryMixin、ServiceMixin

mixin 机制并非仅用于迁移,LoopBack 4 框架自身的应用类就是由多个 mixin 组合出来的。典型写法如:

export class NoteApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {}
  • RepositoryMixin(见 repository.mixin.ts)为应用添加 repository() 绑定方法,把仓库类注册到 RepositoryBindings.REPOSITORIES 命名空间;
  • ServiceMixin(见 service.mixin.ts)为应用添加服务代理(service proxy)相关能力;
  • BootMixin(见 boot.mixin.ts)为应用添加 boot() 便捷方法并动态绑定 PROJECT_ROOT 与 BOOT_OPTIONS。

参考 examples/todo/src/application.ts 等示例,可以看到这种组合式应用类在真实项目中的完整形态。

实战扩展:带构造逻辑与组件注册的 Mixin

mixin 类工厂函数不仅可以声明属性与方法,还可以在构造器中注入逻辑。例如 examples/log-extension/src/mixins/log.mixin.ts 中的 LogMixin:

export function LogMixin<T extends MixinTarget<Application>>(superClass: T) {
  return class extends superClass {
    constructor(...args: any[]) {
      super(...args);
      if (this.options?.logLevel) {
        this.logLevel(this.options.logLevel);
      }
      this.component(LogComponent);
    }

    logLevel(level: LOG_LEVEL) {
      this.bind(EXAMPLE_LOG_BINDINGS.APP_LOG_LEVEL).to(level);
    }
  };
}

它会在应用实例创建时读取 options.logLevel 并完成相应绑定,同时注册 LogComponent 组件。注意 mixin 类的构造器参数必须写成 ...args: any<a href="https://link.gitcode.com/i/854f34d38fb4ddd6a154d0b4c2959732" target="_blank">] 再透传给 super(...args),这是为了让 TypeScript 接受"基类构造签名未知"的通用 mixin 场景。该示例配套的单元测试见 [examples/log-extension/src/tests/unit/mixins/log.mixin.unit.ts,可作为自定义 mixin 的测试范本。

总结

正如上面的示例所示,把 mixin 从 LoopBack 3 迁移到 LoopBack 4 相对直接,核心思路是使用类工厂函数:

  • 属性 Mixin:定义一个接收基类的工厂函数,在具名内部类中用 @property 声明新属性,再让模型继承 工厂函数(BaseEntity);
  • 方法 Mixin(仓库层):定义实现公共接口(如 FindByTitle<M>)的工厂函数,把 findByTitle 落在 CrudRepository 之上;
  • 方法 Mixin(控制器层):定义接收 superClass 与 options 的工厂函数,用 @get、@param 等装饰器声明端点,并统一通过 this.repository 访问数据访问层。

迁移时只需记住三个要点:泛型约束使用 MixinTarget<T>;mixin 类必须是具名声明(装饰器限制);需要访问父类受保护成员或覆盖方法时用 @ts-ignore 注释。掌握了这套模式,你不仅能平滑迁移旧项目,还能像框架内置的 BootMixin、RepositoryMixin、ServiceMixin 一样,为团队沉淀可复用的横向扩展能力。

登录后查看全文
loopback-next