阅读本文前,需要提前阅读前置内容:
一、Midway 增删改查
二、Midway 增删改查的封装及工具类
三、Midway 接口安全认证
四、Midway 集成 Swagger 以及支持JWT bearer
五、Midway 中环境变量的使用
问题
- 大多数情况,所有实体类都有统一字段,需要抽取实体模型的基类;
- 需要将Service的基本操作封装起来;
- 需要将Controller的基本操作封装起来
抽取Entity基类
- 创建目录
common
; - 创建基类
src/common/BaseEntity.ts
;
// src/common/BaseEntity.ts
import {
Column, CreateDateColumn, PrimaryColumn, UpdateDateColumn } from 'typeorm';
export class BaseEntity {
@PrimaryColumn({
type: 'bigint' })
id: number;
@Column({
type: 'bigint' })
updaterId: number;
@Column({
type: 'bigint' })
createrId: number;
@CreateDateColumn()
createTime: Date;
@UpdateDateColumn()
updateTime: Date;
}
- 调整实体类
src/entity/user.ts
;
继承BaseEntity
,并删除user.ts
中的通用字段。
// src/entity/user.ts
import {
EntityModel } from '@midwayjs/orm';
import {
Column } from 'typeorm';
import {
BaseEntity } from '../common/BaseEntity';
@EntityModel('user')
export class User extends BaseEntity {
@Column({
length: 100, nullable: true })
avatarUrl: string;
@Column({
length: 20, unique: true })
username: string;
@Column({
length: 200 })
password: string;
@Column({
length: 20 })
phoneNum: string;
@Column()
regtime: Date;
@Column({
type: 'int', default: 1 })
status: number;
}
抽取Service基类
创建基类src/common/BaseService.ts
;
// src/common/BaseService.ts
import {
In, Repository } from 'typeorm';
import {
BaseEntity } from './BaseEntity';
import {
FindOptionsWhere } from 'typeorm/find-options/FindOptionsWhere';
export abstract class BaseService<T extends BaseEntity> {
abstract getModel(): Repository<T>;
async save(o: T) {
if (!o.id) o.id = new Date().getTime();
return this.getModel().save(o);
}
async delete(id: number) {
return this.getModel().delete(id);
}
async findById(id: number): Promise<T> {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return this.getModel().findOneBy({
id });
}
async findByIds(ids: number[]): Promise<T[]> {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return this.getModel().findBy({
id: In(ids) });
}
async findOne(where: FindOptionsWhere<T>): Promise<T> {
return this.getModel().findOne({
where });
}
}
- 基类定义为抽象类
abstract
,并添加抽象接口abstract getModel()
; <T extends BaseEntity>
泛型用法,定义T
为BaseEntity
的子类;
调整src/service/user.service.ts
;
import {
Provide } from '@midwayjs/decorator';
import {
User } from '../eneity/user';
import {
InjectEntityModel } from '@midwayjs/orm';
import {
Repository } from 'typeorm';
import {
BaseService } from