Rya*_*iss 2 generics typescript typeorm nestjs
我一直很难让子实体使用 REST api 自动工作。
我有一个基类:
class Block {
@PrimaryGeneratedColumn('uuid')
public id: string;
@Column()
public type: string;
}
Run Code Online (Sandbox Code Playgroud)
然后将其扩展到其他块类型,例如:
@Entity('sites_blocks_textblock')
class TextBlock extends Block {
@Column()
public text: string;
}
Run Code Online (Sandbox Code Playgroud)
我让每个块类型都有自己的实体,以便列可以正确序列化到数据库,并对每个属性进行验证。
所以...我有 10 多个块类型,并且我试图避免使用单独的控制器和 CRUD 端点来每个块类型。我只想要一个 BlockController、一个 /block 端点、POST 来创建,然后 PUT 到 /block/:id 上进行更新,这样它就可以从请求的“type”主体参数推断出块的类型。
问题是,在请求中,最后一个 @Body() 参数将不会验证(请求不会通过),除非我使用类型“any”...因为每个自定义块类型都传递它的额外/自定义属性。否则,我将不得不使用每个特定的 Block 子类作为参数类型,需要为每种类型提供自定义方法。
为了实现这一目标,我尝试使用自定义验证管道和泛型,我可以在其中查看传入的“类型”主体参数,并将传入数据强制转换或实例化为特定的块类型。
控制器处理程序:
@Post()
@UseGuards(PrincipalGuard)
public create(@Principal() principal: User,
@Param('siteId', ParseUUIDPipe) siteId: string,
@Body(new BlockValidationPipe()) blockCreate: any): Promise<Block> {
return this.blockService.create(principal.organization, siteId, blockCreate);
}
Run Code Online (Sandbox Code Playgroud)
BlockValidationPipe(这应该将传入数据对象转换为特定的块类型,然后验证它,以该类型返回传入数据对象):
@Injectable()
export class BlockValidationPipe implements PipeTransform<any> {
async transform(value: any, { metatype }: ArgumentMetadata) {
if (value.type) {
if (value.type.id) {
metatype = getBlockTypeFromId(value.type.id);
}
}
if (!metatype || !this.toValidate(metatype)) {
return value;
}
// MAGIC: ==========>
let object = objectToBlockByType(value, value.type.id, metatype);
const errors = await validate(object);
if (errors.length > 0) {
throw new BadRequestException(errors, 'Validation failed');
}
return object ? object : value;
}
private toValidate(metatype: Function): boolean {
const types: Function[] = [String, Boolean, Number, Array, Object];
return !types.includes(metatype);
}
}
Run Code Online (Sandbox Code Playgroud)
使用这个助手(但它可能无法完全按照预期工作,还没有完全传递类型):
function castOrNull<C extends Block>(value: C, type): C | null {
return value as typeof type;
}
export function objectToBlockByType(object, typeId, metatype) {
switch(typeId) {
case 'text':
return castOrNull<TextBlock>(object, TextBlock);
case 'avatar':
return castOrNull<AvatarBlock>(object, AvatarBlock);
case 'button':
return castOrNull<ButtonBlock>(object, ButtonBlock);
// etc....
default:
return castOrNull<Block>(object, Block);
}
}
Run Code Online (Sandbox Code Playgroud)
...这一切都应该为我提供一个适当的块子类实例化以供控制器使用,但我不确定如何将此特定子类类型传递给底层服务调用以更新每个实体类型的特定块存储库。使用泛型可以做到这一点吗?
例如,在 BlockService 中,但我应该将特定的块类型(TextBlock、ButtonBlock 等)传递给repository.save() 方法,以便它将子类类型正确序列化到各自的表中。我假设这是可以做到的,但是如果我错了,请有人纠正我......
我正在尝试这样做,我将块数据作为其块父类型传递,然后尝试获取其特定的类类型来传递以保存,但它不起作用......
public async create(organization: Organization, siteId: string, blockCreate: Block): Promise<Block> {
let blockType: Type<any> = getBlockTypeFromId(blockCreate.type.id);
console.log("create block", typeof blockCreate, blockCreate.constructor.name, blockCreate, typeof blockType, blockType);
///
let r = await this.blockRepository.save<typeof blockCreate>({
organization: organization,
site: await this.siteService.getByIdAndOrganization(siteId, organization),
type: await this.blockTypeService.getById(blockCreate.type.id),
...blockCreate
});
//r.data = JSON.parse(r.data);
return r;
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是“typeof blockCreate”总是返回“object”,我必须调用“blockCreate.constructor.name”来获取正确的子类块类型名称,但无法将其作为类型 T 传递。
所以我想知道...是否有办法将子类类型 T 参数从控制器助手(应该在其中转换并验证子类型)一路返回到存储库,以便我可以将此类型 T 传递到保存(实体)调用...并且正确提交了吗?或者,如果“typeof block”不返回特定的子类类型,是否有其他方法可以从对象实例本身获取此类型 T?我认为在编译时不可能做到前者......?
我真的只是想让子类序列化和验证与一组控制器端点和服务层/存储库调用一起工作......我应该研究部分实体吗?
有人知道我可以寻找什么方向来实现这一目标吗?
让我们简单地设置两个基类/泛型类:
每个都具有以下通用类型: <E> - 用于实体通用类型。
然后,您只需为您的特定实体扩展它们并提供实体即可。
请注意,本质上,整个事情只是围绕 TypeOrm 提供的功能的几个通用包装类。
这是这个想法的骨架,但我测试了它们,它们对我来说效果很好。(代码带有注释)。
让我们从具有一些常见 db / REST 功能的通用服务类开始:
import { Repository, DeepPartial, SaveOptions } from "typeorm";
import { Injectable } from '@nestjs/common';
/**
* Provides common/general functionality for working with db data
* via TypeOrm API.
*
* see:
* https://github.com/typeorm/typeorm/blob/master/docs/repository-api.md
*
* You can extend this service class for functionalities specific
* to your given Entity.
*
* A service is the work-horse for handling the tasks
* (such as fetching the data from data source / db)
* delegated by a controller.
* The service is injected in the controller who delegates the tasks
* to the service for specific data sets / Entities / db tables.
*/
@Injectable()
export class DbGenService<E> {
/**
* @param repo
* is TypeOrm repository for your given Entity <E>.
* (the intermediary object, which does all the work on the db end).
*/
constructor(readonly repo: Repository<E>) {}
/**
* (AUX function to create entity object):
* Creates a new entity/entities and copies all entity properties
* from given objects into their new entities.
* Note that it copies only properties that are present in the entity schema.
* @param obj
*/
async createE(obj): Promise<E[]> {
return this.repo.create(obj);
}
/**
* (AUX function to merge two entity objects, 1st can be set empty):
* Merges multiple entities (or entity-like objects) into a given entity.
*
* @param mergeIntoEntity
* the initial / source and
* finally the target/resulting/merged entity
* Can be initilized with an empty object e.g:
* let e: E = {} as E;
* @param entityLikes
* partial entity or an object looking like the entity
*/
async mergeEs(mergeIntoEntity: E, ...entityLikes: DeepPartial<E>[]): Promise<E> {
return this.repo.merge(mergeIntoEntity, ...entityLikes);
}
/**
* Saves a given entity in the database.
* If entity does not exist in the database,
* then inserts, otherwise updates.
*/
async saveRecord(recordEntity: E): Promise<E> {
return await this.repo.save(recordEntity);
}
/**
* Saves all given entities (array) in the database.
* If entities do not exist in the database,
* then inserts, otherwise updates.
*/
async saveRecords<T extends DeepPartial<E>>(entities: T[], options?: SaveOptions): Promise<(T & E)[]> {
return await this.repo.save(entities, options);
}
/**
* Return all the records of the db table for this Entity
*/
async getAllRecords(): Promise<E[]> {
return await this.repo.find();
}
/**
* Return the record of the db table for this Entity
* having
* @param id = id
*/
async getRecordById(recID: number): Promise<E> {
return await this.repo.findOne(recID);
}
/**
* Deletes the records of the db table for this Entity
* having query statement:
* @param query = query
*/
async deleteAllRecords(): Promise<void> {
await this.repo.clear();
}
/**
* deletes the record of the db table for this Entity
* having
* @param id = id
*/
async deleteRecord(id): Promise<void> {
await this.repo.delete(id);
}
// ... + add your common db functions here
// and match them with the generic controller ....
}
Run Code Online (Sandbox Code Playgroud)
接下来,您编写一个通用控制器,它将工作负载委托给服务 - 匹配服务功能 - 如下所示:
import { DeepPartial } from 'typeorm';
import { Controller, Get, Query, Post, Body, Put, Param, Delete } from '@nestjs/common';
import { DbGenService } from './db-gen.service';
/**
* General/base controller - handles basic HTTP requests of:
* Get, Query, Post, Body, Put, Param, Delete.
*
* Provides general/base/shared db functionality
* (layed out in the service class: DbGenService<E> - via TypeOrm API)
* to exteded controllers of this DbGenController class.
*
* You can use this controller as a base class for your
* specific controllers that share the same functionalities
* with this controller.
*
* Simply extend it like this:
*
* @Controller('myRoute')
* export class MyController extends DbGenController<MyEntity> { ... }
*
* the extended router than handles requests such as
* e.g:
* http://localhost:3000/myRoute
* http://localhost:3000/myRoute/1
*
*
*/
@Controller()
export class DbGenController<E> {
/**
* DbGenService is the class with the generic working functions
* behind the controller
*/
constructor(private dbGenService: DbGenService<E>) {}
/**
* Saves all given entities (array) in the database.
* If entities do not exist in the database,
* then inserts, otherwise updates.
*/
@Post()
async saveRecord(@Body() dto: DeepPartial<E>) {
// create the Entity from the DTO
let e: E[] = await this.dbGenService.createE(dto);
// OR:
// let e: E = {} as E;
// e = await this.dbGenService.mergeEs(e, dto);
const records = await this.dbGenService.saveRecords(e);
return records;
}
/**
* Return all the records of the db table for this Entity
*/
@Get()
async getAllRecords(): Promise<E[]> {
const records = await this.dbGenService.getAllRecords();
return records;
}
/**
* Return the record of the db table for this Entity
* having
* @param id = id
*/
@Get(':id')
async getRecordById(@Param('id') id): Promise<E> {
const records = await this.dbGenService.getRecordById(id);
return records;
}
/**
* Return the record of the db table for this Entity
* having
* @param id = id
*/
@Get()
async getRecordByFVs(@Param('id') id): Promise<E> {
const records = await this.dbGenService.getRecordById(id);
return records;
}
/**
* Deletes all the records of the db table for this Entity
*/
@Delete()
async deleteAllRecords(): Promise<void> {
const records = await this.dbGenService.deleteAllRecords();
return records;
}
/**
* Deletes the records of the db table for this Entity
* having query statement:
* @param query = query
*/
@Delete()
async deleteRecord(@Query() query): Promise<void> {
const records = await this.dbGenService.deleteRecord(query.ID);
return records;
}
/**
* Deletes the record of the db table for this Entity
* having
* @param id = id
*/
@Delete(':id')
deleteRecordById(@Param('id') id): Promise<void> {
return this.dbGenService.deleteRecord(id);
}
}
Run Code Online (Sandbox Code Playgroud)
...现在是美丽/有趣的部分 - 将它们用于您想要的任何实体 - 例如 UsersEntity - 服务:
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Injectable } from '@nestjs/common';
import { DbGenService } from '../../generic/db-gen.service';
import { UsersEntity } from '../../../entities/users.entity';
/**
* Users db records service.
*
* General doc:
* ------------
* A db service is the work-horse for handling the tasks
* (such as fetching the data from data source / db)
* delegated by a controller.
* The service is injected in the controller.
*
* This service extends the usege of the common/generic
* db taks/functions of the service class: DbGenService<E>,
* where <E> is the given Entity type, which we we pass to the
* DbGenService instance, reflecting so exactly the Entity
* of this extended class - in this case the: UsersEntity
*/
@Injectable()
export class UsersService<UsersEntity> extends DbGenService<UsersEntity> {
constructor(@InjectRepository(UsersEntity) repo: Repository<UsersEntity>) {
super(repo);
}
}
Run Code Online (Sandbox Code Playgroud)
现在 UsersEntity - 控制器:
import { Controller } from '@nestjs/common';
import { appCfg } from '../../../../config/app-config.service';
import { DbGenController } from '../../generic/db-gen.controller';
import { UsersEntity } from '../../../entities/users.entity';
import { UsersService } from './users.service';
/**
* Controller - handles HTTP requests.
*
* This controller handles routes of HTTP requests with suffix:
* /users
* due to the decorator:
* @Controller('users')
* e.g:
* http://localhost:3000/users
* http://localhost:3000/users/1
*
* This service extends the usage of the common/generic
* db controller class: DbGenController<E>,
* where <E> is the given Entity type, which we we pass to the
* DbGenController instance, reflecting so exactly the Entity
* of this extended class - in this case the: UsersEntity
*/
@Controller('users')
export class UsersController extends DbGenController<UsersEntity> {
constructor(private usersService: UsersService<UsersEntity>) {
super(usersService);
}
}
Run Code Online (Sandbox Code Playgroud)
...当然,将其链接在一起:
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { UsersEntity } from '../../../entities/users.entity';
import { TypeOrmModule } from '@nestjs/typeorm';
/**
* UsersModule is used to export the UsersService,
* so that other modules, specifically the AuthModule,
* can communicate with the database to perform
* its user authentication functions via an access to UsersService.
*/
@Module({
imports: [TypeOrmModule.forFeature([UsersEntity])],
controllers: [UsersController],
providers: [UsersService]
})
export class UsersModule {}
Run Code Online (Sandbox Code Playgroud)
与“UsersEntity”类似,您现在可以将通用服务和通用控制器中放置的所有上述 REST 功能应用到任何其他实体,而无需在其控制器或服务内重写任何功能。而且,您仍然可以灵活地将特定的 REST / 数据库功能应用于各个扩展类内的每个实体控制器/服务。
现在,请记住,这只是一个基本的框架设计,需要所有其他必需品,但应该让您开始使用这种方法,这可能适合某些人,也可能不适合某些人。
REST 示例的一些语法直接来自 NestJs 文档/网站。
(TS大师们请随时提供改进、建议等,特别是在装饰器方面,我很幸运在这里经历过......)
| 归档时间: |
|
| 查看次数: |
8458 次 |
| 最近记录: |