-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathget-grouped-blueprints.usecase.ts
75 lines (57 loc) · 2.66 KB
/
get-grouped-blueprints.usecase.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
import { Injectable, NotFoundException } from '@nestjs/common';
import { NotificationTemplateEntity, NotificationTemplateRepository } from '@novu/dal';
import { buildGroupedBlueprintsKey, CachedResponse, PinoLogger } from '@novu/application-generic';
import { IGroupedBlueprint } from '@novu/shared';
import { GroupedBlueprintResponse } from '../../dto/grouped-blueprint.response.dto';
import { GetGroupedBlueprintsCommand, POPULAR_GROUPED_NAME, POPULAR_TEMPLATES_ID_LIST } from './index';
const WEEK_IN_SECONDS = 60 * 60 * 24 * 7;
@Injectable()
export class GetGroupedBlueprints {
constructor(
private notificationTemplateRepository: NotificationTemplateRepository,
private logger: PinoLogger
) {
this.logger.setContext(this.constructor.name);
}
@CachedResponse({
builder: (command: GetGroupedBlueprintsCommand) => buildGroupedBlueprintsKey(command.environmentId),
options: { ttl: WEEK_IN_SECONDS },
})
async execute(command: GetGroupedBlueprintsCommand): Promise<GroupedBlueprintResponse> {
const generalGroups = await this.fetchGroupedBlueprints();
const updatePopularBlueprints = this.getPopularGroupBlueprints(generalGroups);
const popularGroup = { name: POPULAR_GROUPED_NAME, blueprints: updatePopularBlueprints };
return { general: generalGroups as IGroupedBlueprint[], popular: popularGroup as IGroupedBlueprint };
}
private async fetchGroupedBlueprints() {
const groups = await this.notificationTemplateRepository.findAllGroupedByCategory();
if (!groups?.length) {
throw new NotFoundException(
`Blueprints for organization id ${NotificationTemplateRepository.getBlueprintOrganizationId()} were not found`
);
}
return groups;
}
private groupedToBlueprintsArray(groups: { name: string; blueprints: NotificationTemplateEntity[] }[]) {
return groups.map((group) => group.blueprints).flat();
}
private getPopularGroupBlueprints(
groups: { name: string; blueprints: NotificationTemplateEntity[] }[]
): NotificationTemplateEntity[] {
const storedBlueprints = this.groupedToBlueprintsArray(groups);
const localPopularIds = [...POPULAR_TEMPLATES_ID_LIST];
const result: NotificationTemplateEntity[] = [];
for (const localPopularId of localPopularIds) {
const storedBlueprint = storedBlueprints.find((blueprint) => blueprint._id === localPopularId);
if (!storedBlueprint) {
this.logger.warn(
`Could not find stored popular blueprint id: ${localPopularId}, BLUEPRINT_CREATOR:
${NotificationTemplateRepository.getBlueprintOrganizationId()}`
);
continue;
}
result.push(storedBlueprint);
}
return result;
}
}