-
Notifications
You must be signed in to change notification settings - Fork 142
/
class-transformer.assembler.ts
78 lines (69 loc) · 2.61 KB
/
class-transformer.assembler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { plainToClass } from 'class-transformer';
import { AggregateQuery, AggregateResponse, Query } from '../interfaces';
import { AbstractAssembler } from './abstract.assembler';
import { Class, DeepPartial } from '../common';
import { getAssemblerSerializer } from './assembler.serializer';
import { getAssemblerDeserializer } from './assembler.deserializer';
/**
* Base assembler that uses class-transformer to transform to and from the DTO/Entity.
*/
export abstract class ClassTransformerAssembler<DTO, Entity> extends AbstractAssembler<
DTO,
Entity,
DeepPartial<DTO>,
DeepPartial<Entity>,
DeepPartial<DTO>,
DeepPartial<Entity>
> {
convertToDTO(entity: Entity): DTO {
return this.convert(this.DTOClass, this.toPlain(entity));
}
convertToEntity(dto: DTO): Entity {
return this.convert(this.EntityClass, this.toPlain(dto));
}
convertQuery(query: Query<DTO>): Query<Entity> {
return query as Query<Entity>;
}
convertAggregateQuery(aggregate: AggregateQuery<DTO>): AggregateQuery<Entity> {
return aggregate as unknown as AggregateQuery<Entity>;
}
convertAggregateResponse(aggregate: AggregateResponse<Entity>): AggregateResponse<DTO> {
return aggregate as AggregateResponse<DTO>;
}
convertToCreateEntity(create: DeepPartial<DTO>): DeepPartial<Entity> {
return this.convert(this.EntityClass, create);
}
convertToUpdateEntity(create: DeepPartial<DTO>): DeepPartial<Entity> {
return this.convert(this.EntityClass, create);
}
// eslint-disable-next-line @typescript-eslint/ban-types
convert<T>(cls: Class<T>, obj: object): T {
const deserializer = getAssemblerDeserializer(cls);
if (deserializer) {
return deserializer(obj);
}
return plainToClass(cls, obj);
}
// eslint-disable-next-line @typescript-eslint/ban-types
toPlain(entityOrDto: Entity | DTO): object {
if (entityOrDto && entityOrDto instanceof this.EntityClass) {
const serializer = getAssemblerSerializer(this.EntityClass);
if (serializer) {
return serializer(entityOrDto);
}
} else if (entityOrDto instanceof this.DTOClass) {
const serializer = getAssemblerSerializer(this.DTOClass);
if (serializer) {
return serializer(entityOrDto);
}
} else if ('constructor' in entityOrDto) {
// eslint-disable-next-line @typescript-eslint/ban-types
const serializer = getAssemblerSerializer((entityOrDto as object).constructor as Class<unknown>);
if (serializer) {
return serializer(entityOrDto);
}
}
// eslint-disable-next-line @typescript-eslint/ban-types
return entityOrDto as unknown as object;
}
}