-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdbHelper.ts
More file actions
181 lines (162 loc) · 5.04 KB
/
dbHelper.ts
File metadata and controls
181 lines (162 loc) · 5.04 KB
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import { Collection, Db, ObjectId } from 'mongodb';
import { ProjectDBScheme, WorkspaceDBScheme } from '@hawk.so/types';
import { WorkspaceWithTariffPlan } from '../types';
import HawkCatcher from '@hawk.so/nodejs';
import { CriticalError } from '../../../lib/workerErrors';
/**
* Class that implements methods used for interaction between limiter and db
*/
export class DbHelper {
/**
* Connection to events DB
*/
private eventsDbConnection: Db;
/**
* Collection with projects
*/
private projectsCollection: Collection<ProjectDBScheme>;
/**
* Collection with workspaces
*/
private workspacesCollection: Collection<WorkspaceDBScheme>;
/**
* @param projects - projects collection
* @param workspaces - workspaces collection
* @param eventsDbConnection - connection to events DB
*/
constructor(projects: Collection<ProjectDBScheme>, workspaces: Collection<WorkspaceDBScheme>, eventsDbConnection: Db) {
this.eventsDbConnection = eventsDbConnection;
this.projectsCollection = projects;
this.workspacesCollection = workspaces;
}
/**
* Method that returns all workspaces with their tariff plans
*/
public async getWorkspacesWithTariffPlans():Promise<WorkspaceWithTariffPlan[]>;
/**
* Method that returns workspace with its tariff plan by its id
*
* @param id - id of the workspace to fetch
*/
public async getWorkspacesWithTariffPlans(id: string):Promise<WorkspaceWithTariffPlan>;
/**
* Returns workspace with its tariff plan by its id
*
* @param id - workspace id
*/
public async getWorkspacesWithTariffPlans(id?: string):Promise<WorkspaceWithTariffPlan[] | WorkspaceWithTariffPlan> {
/* eslint-disable-next-line */
const queue: any[] = [
{
$lookup: {
from: 'plans',
localField: 'tariffPlanId',
foreignField: '_id',
as: 'tariffPlan',
},
},
{
$unwind: {
path: '$tariffPlan',
},
},
];
if (id !== undefined) {
queue.unshift({
$match: {
_id: new ObjectId(id),
},
});
}
const workspacesArray = await this.workspacesCollection.aggregate<WorkspaceWithTariffPlan>(queue).toArray();
return (id !== undefined) ? workspacesArray[0] : workspacesArray;
}
/**
* Updates workspaces data in Database
*
* @param workspacesToUpdate - array of workspaces to be updated
*/
public async updateWorkspacesEventsCountAndIsBlocked(workspacesToUpdate: WorkspaceWithTariffPlan[]): Promise<void> {
if (workspacesToUpdate.length === 0) {
return;
}
const operations = workspacesToUpdate.map(workspace => {
return {
updateOne: {
filter: {
_id: workspace._id,
},
update: {
$set: {
billingPeriodEventsCount: workspace.billingPeriodEventsCount,
isBlocked: workspace.isBlocked,
},
},
},
};
});
await this.workspacesCollection.bulkWrite(operations);
}
/**
* Returns total event counts for last billing period
*
* @param project - project to check
* @param since - timestamp of the time from which we count the events
*/
public async getEventsCountByProject(
project: ProjectDBScheme,
since: number
): Promise<number> {
try {
const repetitionsCollection = this.eventsDbConnection.collection('repetitions:' + project._id.toString());
const eventsCollection = this.eventsDbConnection.collection('events:' + project._id.toString());
const query = {
$or: [ {
timestamp: {
$gt: since,
},
},
{
'payload.timestamp': {
$gt: since,
},
} ],
};
const repetitionsCount = await repetitionsCollection.countDocuments(query);
const originalEventCount = await eventsCollection.countDocuments(query);
return repetitionsCount + originalEventCount;
} catch (e) {
HawkCatcher.send(e);
throw new CriticalError(e);
}
}
/**
* Calculates total events count for all provided projects since the specific date
*
* @param projects - projects to calculate for
* @param since - timestamp of the time from which we count the events
*/
public async getEventsCountByProjects(projects: ProjectDBScheme[], since: number): Promise<number> {
const sum = (array: number[]): number => array.reduce((acc, val) => acc + val, 0);
return Promise.all(projects.map(
project => this.getEventsCountByProject(project, since)
))
.then(sum);
}
/**
* Returns all projects from Database or projects of the specified workspace
*
* @param [workspaceId] - workspace ids to fetch projects that belongs that workspace
*/
public getProjects(workspaceId?: string): Promise<ProjectDBScheme[]> {
const query = workspaceId
? {
$or: [
{ workspaceId: workspaceId },
{ workspaceId: new ObjectId(workspaceId) },
],
}
: {};
return this.projectsCollection.find(query).toArray();
}
}