forked from Sairyss/domain-driven-hexagon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
typeorm.repository.base.ts
159 lines (140 loc) · 4.57 KB
/
typeorm.repository.base.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import { FindConditions, ObjectLiteral, Repository } from 'typeorm';
import { ID } from '@libs/ddd/domain/value-objects/id.value-object';
import { DomainEvents } from '@libs/ddd/domain/domain-events';
import { Logger } from '@libs/ddd/domain/ports/logger.port';
import { AggregateRoot } from '@libs/ddd/domain/base-classes/aggregate-root.base';
import {
QueryParams,
FindManyPaginatedParams,
RepositoryPort,
DataWithPaginationMeta,
} from '../../../domain/ports/repository.ports';
import { NotFoundException } from '../../../../exceptions';
import { OrmMapper } from './orm-mapper.base';
export type WhereCondition<OrmEntity> =
| FindConditions<OrmEntity>[]
| FindConditions<OrmEntity>
| ObjectLiteral
| string;
export abstract class TypeormRepositoryBase<
Entity extends AggregateRoot<unknown>,
EntityProps,
OrmEntity
> implements RepositoryPort<Entity, EntityProps> {
protected constructor(
protected readonly repository: Repository<OrmEntity>,
protected readonly mapper: OrmMapper<Entity, OrmEntity>,
protected readonly logger: Logger,
) {}
protected abstract relations: string[];
protected tableName = this.repository.metadata.tableName;
protected abstract prepareQuery(
params: QueryParams<EntityProps>,
): WhereCondition<OrmEntity>;
async save(entity: Entity): Promise<Entity> {
const ormEntity = this.mapper.toOrmEntity(entity);
const result = await this.repository.save(ormEntity);
await DomainEvents.publishEvents(
entity.id,
this.logger,
this.correlationId,
);
this.logger.debug(
`[${entity.constructor.name}] persisted ${entity.id.value}`,
);
return this.mapper.toDomainEntity(result);
}
async saveMultiple(entities: Entity[]): Promise<Entity[]> {
const ormEntities = entities.map(entity => this.mapper.toOrmEntity(entity));
const result = await this.repository.save(ormEntities);
await Promise.all(
entities.map(entity =>
DomainEvents.publishEvents(entity.id, this.logger, this.correlationId),
),
);
this.logger.debug(
`[${entities}]: persisted ${entities.map(entity => entity.id)}`,
);
return result.map(entity => this.mapper.toDomainEntity(entity));
}
async findOne(
params: QueryParams<EntityProps> = {},
): Promise<Entity | undefined> {
const where = this.prepareQuery(params);
const found = await this.repository.findOne({
where,
relations: this.relations,
});
return found ? this.mapper.toDomainEntity(found) : undefined;
}
async findOneOrThrow(params: QueryParams<EntityProps> = {}): Promise<Entity> {
const found = await this.findOne(params);
if (!found) {
throw new NotFoundException();
}
return found;
}
async findOneByIdOrThrow(id: ID | string): Promise<Entity> {
const found = await this.repository.findOne({
where: { id: id instanceof ID ? id.value : id },
});
if (!found) {
throw new NotFoundException();
}
return this.mapper.toDomainEntity(found);
}
async findMany(params: QueryParams<EntityProps> = {}): Promise<Entity[]> {
const result = await this.repository.find({
where: this.prepareQuery(params),
relations: this.relations,
});
return result.map(item => this.mapper.toDomainEntity(item));
}
async findManyPaginated({
params = {},
pagination,
orderBy,
}: FindManyPaginatedParams<EntityProps>): Promise<
DataWithPaginationMeta<Entity[]>
> {
const [data, count] = await this.repository.findAndCount({
skip: pagination?.skip,
take: pagination?.limit,
where: this.prepareQuery(params),
order: orderBy,
relations: this.relations,
});
const result: DataWithPaginationMeta<Entity[]> = {
data: data.map(item => this.mapper.toDomainEntity(item)),
count,
limit: pagination?.limit,
page: pagination?.page,
};
return result;
}
async delete(entity: Entity): Promise<Entity> {
await this.repository.remove(this.mapper.toOrmEntity(entity));
await DomainEvents.publishEvents(
entity.id,
this.logger,
this.correlationId,
);
this.logger.debug(
`[${entity.constructor.name}] deleted ${entity.id.value}`,
);
return entity;
}
protected correlationId?: string;
setCorrelationId(correlationId: string): this {
this.correlationId = correlationId;
this.setContext();
return this;
}
private setContext() {
if (this.correlationId) {
this.logger.setContext(`${this.constructor.name}:${this.correlationId}`);
} else {
this.logger.setContext(this.constructor.name);
}
}
}