-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patheventsFactory.js
More file actions
892 lines (775 loc) · 24.8 KB
/
eventsFactory.js
File metadata and controls
892 lines (775 loc) · 24.8 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
import { getMidnightWithTimezoneOffset, getUTCMidnight } from '../utils/dates';
import safe from 'safe-regex';
import { createProjectEventsByIdLoader } from '../dataLoaders';
import { Effect, sgr } from '../utils/ansi';
const Factory = require('./modelFactory');
const mongo = require('../mongo');
const Event = require('../models/event');
const { ObjectID } = require('mongodb');
import RedisHelper from '../redisHelper';
const { composeEventPayloadByRepetition } = require('../utils/merge');
const MAX_DB_READ_BATCH_SIZE = Number(process.env.MAX_DB_READ_BATCH_SIZE);
/**
* @typedef {import('mongodb').UpdateWriteOpResult} UpdateWriteOpResult
*/
/**
* @typedef {Object} EventRepetitionSchema
* @property {String} _id — repetition's identifier
* @property {String} groupHash - event's hash. Generates according to the rule described in EventSchema
* @property {EventPayload} payload - repetition's payload
* @property {Number} timestamp - repetition's Unix timestamp
* @property {Number} originalTimestamp - UNIX timestmap of the original event
* @property {String} originalEventId - id of the original event
* @property {String} projectId - id of the project, which repetition it is
*/
/**
* @typedef {Object} EventRepetitionsPortionSchema
* @property {EventRepetitionSchema[]} repetitions - list of repetitions
* @property {String | null} nextCursor - pointer to the first repetition of the next portion, null if there are no repetitions left
*/
/**
* @typedef {Object} DailyEventSchema
* @property {String} _id - id of the dailyEvent
* @property {String} groupHash - group hash of the dailyEvent
* @property {Number} groupingTimestamp - UNIX timestamp that represents the day of dailyEvent
* @property {Number} affectedUsers - number of users affected this day
* @property {Number} count - number of events this day
* @property {String} lastRepetitionId - id of the last repetition this day
* @property {Number} lastRepetitionTime - UNIX timestamp that represent time of the last repetition this day
* @property {Event} event - one certain event that represents all of the repetitions this day
*/
/**
* @typedef {Object} DailyEventsCursor
* @property {Number} groupingTimestampBoundary - boundary value of groupingTimestamp field of the last event in the portion
* @property {Number} sortValueBoundary - boundary value of the field by which events are sorted (count/affectedUsers/lastRepetitionTime) of the last event in the portion
* @property {String} idBoundary - boundary value of _id field of the last event in the portion
*/
/**
* @typedef {Object} DaylyEventsPortionSchema
* @property {DailyEventSchema[]} dailyEvents - original event of the daily one
* @property {DailyEventsCursor | null} nextCursor - object with boundary values of the first event in the next portion
*/
/**
* @typedef {Object} EventsFilters
* @property {boolean} [starred] - if true, events with 'starred' mark should be included to the output
* @property {boolean} [resolved] - if true, events with 'resolved' should be included to the output
* @property {boolean} [ignored] - if true, events with 'ignored' mark should be included to the output
*/
/**
* EventsFactory
*
* Factory Class for Event's Model
*/
class EventsFactory extends Factory {
/**
/**
* Redis helper instance for modifying data through redis
*/
redis = new RedisHelper();
/**
* Event types with collections where they stored
* @return {{EVENTS: string, DAILY_EVENTS: string, REPETITIONS: string, RELEASES: string}}
* @constructor
*/
get TYPES() {
return {
EVENTS: 'events',
REPETITIONS: 'repetitions',
DAILY_EVENTS: 'dailyEvents',
RELEASES: 'releases',
};
}
/**
* Creates Event instance
* @param {ObjectId} projectId - project ID
*/
constructor(projectId) {
super();
if (!projectId) {
throw new Error('Can not construct Event model, because projectId is not provided');
}
this.redis.initialize();
this.projectId = projectId;
this.eventsDataLoader = createProjectEventsByIdLoader(mongo.databases.events, this.projectId);
}
/**
* Returns pointer to the collection
*
* @param {String} type - each events in order to optimization holds data in different collections.
* This argument defines which collection need to be used.
*
* @returns {String}
*/
getCollection(type) {
return mongo.databases.events.collection(
type + ':' + this.projectId
);
}
/**
* Is collection of events exists
*
* @param {String} type - type of collection to check
*
* @return {Promise<boolean>}
*/
isCollectionExists(type) {
return mongo.databases.events.listCollections({ name: type + ':' + this.projectId }).hasNext();
}
/**
* Finds events by passed query
*
* @param {object} [query={}] - query
* @param {Number} [limit=10] - query limit
* @param {Number} [skip=0] - query skip
* @returns {Event[]} - events matching query
*/
async find(query = {}, limit = 10, skip = 0) {
limit = this.validateLimit(limit);
skip = this.validateSkip(skip);
const cursor = this.getCollection(this.TYPES.EVENTS)
.find(query)
.sort([ ['_id', -1] ])
.limit(limit)
.skip(skip);
const result = await cursor.toArray();
return result.map(eventSchema => {
return new Event({
...eventSchema,
projectId: this.projectId,
});
});
}
/**
* Find event by id
*
* @param {string|ObjectID} id - event's id
* @returns {Event|null}
*/
async findById(id) {
const searchResult = await this.eventsDataLoader.load(id);
const event = searchResult ? new Event(searchResult) : null;
return event;
}
/**
* Find an event by any custom query
*
* @param {object} query - any custom mongo query
* @return {Event}
*/
async findOneByQuery(query) {
const searchResult = await this.getCollection(this.TYPES.EVENTS)
.findOne(query);
return new Event(searchResult);
}
/**
* Returns events that grouped by day
*
* @param {Number} limit - events count limitations
* @param {DailyEventsCursor} paginationCursor - object that contains boundary values of the last event in the previous portion
* @param {'BY_DATE' | 'BY_COUNT'} sort - events sort order
* @param {EventsFilters} filters - marks by which events should be filtered
* @param {String} search - Search query
* @param {String} release - release name
*
* @return {DaylyEventsPortionSchema}
*/
async findDailyEventsPortion(
limit = 10,
paginationCursor = null,
sort = 'BY_DATE',
filters = {},
search = '',
release
) {
if (typeof search !== 'string') {
throw new Error('Search parameter must be a string');
}
/**
* Check if pattern is safe RegExp
*/
if (!safe(search)) {
throw new Error('Invalid regular expression pattern');
}
switch (sort) {
case 'BY_COUNT':
sort = 'count';
break;
case 'BY_DATE':
sort = 'lastRepetitionTime';
break;
case 'BY_AFFECTED_USERS':
sort = 'affectedUsers';
break;
default:
sort = 'lastRepetitionTime';
break;
}
const escapedSearch = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
limit = this.validateLimit(limit);
const pipeline = [
{
$match: paginationCursor ? {
/**
* This condition is used for cursor-based pagination
* We sort result by groupingTimestamp desc, [sort] desc, _id desc
* So we need to fetch documents that are less than the last document of the previous portion (based on all three conditions)
*/
$or: [
{
/**
* If groupingTimestamp is less than the cursors one
* - daily events of the next day
*/
groupingTimestamp: { $lt: paginationCursor.groupingTimestampBoundary },
},
{
/**
* If groupingTimestamp equals to the cursor one, but [sort] is less than the cursors one
* - daily events of the same day, but with less count/affectedUsers/lastRepetitionTime
*/
$and: [
{ groupingTimestamp: paginationCursor.groupingTimestampBoundary },
{ [sort]: { $lt: paginationCursor.sortValueBoundary } },
],
},
{
/**
* If groupingTimestamp and [sort] equals to the cursors ones, but _id is less or equal to the cursors one
* - daily events of the same day with the same count/affectedUsers/lastRepetitionTime, but that were created earlier
*/
$and: [
{ groupingTimestamp: paginationCursor.groupingTimestampBoundary },
{ [sort]: paginationCursor.sortValueBoundary },
{ _id: { $lte: new ObjectID(paginationCursor.idBoundary) } },
],
},
],
} : {},
},
{
$sort: {
groupingTimestamp: -1,
[sort]: -1,
_id: -1,
},
},
];
const searchFilter = search.trim().length > 0
? {
$or: [
{
'event.payload.title': {
$regex: escapedSearch,
$options: 'i',
},
},
{
'event.payload.backtrace.file': {
$regex: escapedSearch,
$options: 'i',
},
},
{
'event.payload.context': {
$regex: escapedSearch,
$options: 'i',
},
},
{
'event.payload.addons': {
$regex: escapedSearch,
$options: 'i',
},
},
],
}
: {};
const matchFilter = filters
? Object.fromEntries(
Object
.entries(filters)
.map(([mark, exists]) => [`event.marks.${mark}`, { $exists: exists } ])
)
: {};
// Filter by release if provided (coerce event payload release to string)
const releaseFilter = release
? {
$expr: {
$eq: [
{
$convert: {
input: '$event.payload.release',
to: 'string',
onError: '',
onNull: '',
},
},
String(release),
],
},
}
: {};
pipeline.push(
/**
* Left outer join original event on groupHash field
*/
{
$lookup: {
from: 'events:' + this.projectId,
localField: 'groupHash',
foreignField: 'groupHash',
as: 'event',
},
},
{
$lookup: {
from: 'repetitions:' + this.projectId,
localField: 'lastRepetitionId',
foreignField: '_id',
as: 'repetition',
},
},
/**
* Desctruct event and repetition arrays since there are only one document in both arrays
*/
{
$unwind: '$event',
},
{
$unwind: {
path: '$repetition',
preserveNullAndEmptyArrays: true,
},
},
{
$match: {
...matchFilter,
...searchFilter,
...releaseFilter,
},
},
{ $limit: limit + 1 },
{
$unset: 'groupHash',
}
);
const cursor = this.getCollection(this.TYPES.DAILY_EVENTS).aggregate(pipeline);
const result = await cursor.toArray();
let nextCursor;
if (result.length === limit + 1) {
const nextCursorEvent = result.pop();
nextCursor = {
groupingTimestampBoundary: nextCursorEvent.groupingTimestamp,
sortValueBoundary: nextCursorEvent[sort],
idBoundary: nextCursorEvent._id.toString(),
};
}
const composedResult = result.map(dailyEvent => {
const repetition = dailyEvent.repetition;
const event = dailyEvent.event;
dailyEvent.event = this._composeEventWithRepetition(event, repetition);
dailyEvent.id = dailyEvent._id.toString();
delete dailyEvent.repetition;
delete dailyEvent._id;
return dailyEvent;
});
return {
nextCursor: nextCursor,
dailyEvents: composedResult,
};
}
/**
* Get chart data for projects (uses Redis with fallback to MongoDB)
*
* @param {string} startDate - start date (ISO string or Unix timestamp)
* @param {string} endDate - end date (ISO string or Unix timestamp)
* @param {number} groupBy - grouping interval in minutes
* @param {number} timezoneOffset - user's local timezone offset in minutes
* @param {string} projectId - project ID
* @param {string} groupHash - event's group hash (empty for project-level data)
* @returns {Promise<Array>}
*/
async getChartData(startDate, endDate, groupBy = 60, timezoneOffset = 0, projectId = '', groupHash = '') {
try {
const redisData = await this.redis.getChartDataFromRedis(
startDate,
endDate,
groupBy,
timezoneOffset,
projectId,
groupHash
);
if (redisData && redisData.length > 0) {
return redisData;
}
// Fallback to Mongo
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
const days = Math.ceil((end - start) / (24 * 60 * 60 * 1000));
return this.findChartData(days, timezoneOffset, groupHash);
} catch (err) {
console.error('[EventsFactory] getChartData error:', err);
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
const days = Math.ceil((end - start) / (24 * 60 * 60 * 1000));
return this.findChartData(days, timezoneOffset, groupHash);
}
}
/**
* Get chart data from MongoDB only (for events)
*
* @param {number} days - how many days to fetch
* @param {number} timezoneOffset - user's local timezone offset in minutes
* @param {string} groupHash - event's group hash
* @returns {Promise<Array>}
*/
async getChartDataFromMongo(days, timezoneOffset = 0, groupHash = '') {
return this.findChartData(days, timezoneOffset, groupHash);
}
/**
* Fetch timestamps and total count of errors (or target error) for each day since
*
* @param {number} days - how many days we need to fetch for displaying in a chart
* @param {number} timezoneOffset - user's local timezone offset in minutes
* @param {string} groupHash - event's group hash for showing only target event
* @return {ProjectChartItem[]}
*/
async findChartData(days, timezoneOffset = 0, groupHash = '') {
const today = new Date();
const since = today.setDate(today.getDate() - days) / 1000;
/**
* Compose options for find method
* @type {{groupingTimestamp: {$gt: number}}}
*/
const options = {
groupingTimestamp: {
$gt: since,
},
};
/**
* Add eq check if groupHash was passed
*/
if (groupHash) {
options.groupHash = {
$eq: groupHash,
};
}
const dailyEventsCursor = await this.getCollection(this.TYPES.DAILY_EVENTS)
.find(options, {
projection: {
lastRepetitionTime: 1,
groupingTimestamp: 1,
count: 1,
},
})
.batchSize(MAX_DB_READ_BATCH_SIZE);
const groupedCounts = {};
for await (const item of dailyEventsCursor) {
const groupingTimestamp = getMidnightWithTimezoneOffset(
item.lastRepetitionTime,
item.groupingTimestamp,
timezoneOffset
);
const key = `groupingTimestamp:${groupingTimestamp}`;
const current = groupedCounts[key] || 0;
if (item.count === undefined || item.count === null) {
console.warn(`Missing 'count' field for daily event with key ${key}. Defaulting to 0.`);
groupedCounts[key] = current;
} else {
groupedCounts[key] = current + item.count;
}
}
/**
* Now fill all requested days
*/
let result = [];
for (let i = 0; i < days; i++) {
const now = new Date();
const day = new Date(now.setDate(now.getDate() - i));
const dayMidnight = getUTCMidnight(day) / 1000;
let groupedCount = groupedCounts[`groupingTimestamp:${dayMidnight}`];
if (!groupedCount) {
groupedCount = 0;
}
result.push({
timestamp: dayMidnight,
count: groupedCount,
});
}
/**
* Order by time ascendance
*/
result = result.sort((a, b) => a.timestamp - b.timestamp);
return result;
}
/**
* Returns number of documents that occurred after the last visit time
*
* @param {Number} lastVisit - user's last visit time on project
*
* @return {Promise<Number>}
*
* @todo move to Project model
*/
async getUnreadCount(lastVisit) {
const query = {
timestamp: {
$gt: lastVisit,
},
};
return this.getCollection(this.TYPES.EVENTS)
.countDocuments(query);
}
/**
* Returns Event repetitions
*
* @param {string|ObjectID} eventId - Event's id, could be repetitionId in case when we want to get repetitions portion by one repetition
* @param {string|ObjectID} originalEventId - id of the original event
* @param {Number} limit - count limitations
* @param {Number} cursor - pointer to the next repetition
*
* @return {EventRepetitionsPortionSchema}
*/
async getEventRepetitions(originalEventId, limit = 10, cursor = null) {
limit = this.validateLimit(limit);
cursor = cursor ? new ObjectID(cursor) : null;
const result = {
repetitions: [],
nextCursor: null,
};
/**
* Get original event
* @type {Event}
*/
const eventOriginal = await this.findById(originalEventId);
if (!eventOriginal) {
throw new Error(`Original event not found for ${originalEventId}`);
}
/**
* Get portion based on cursor if cursor is not null
*/
const query = cursor ? {
groupHash: eventOriginal.groupHash,
_id: { $lte: cursor },
} : {
groupHash: eventOriginal.groupHash,
};
/**
* Collect repetitions
* @type {EventRepetitionSchema[]}
*/
const repetitions = await this.getCollection(this.TYPES.REPETITIONS)
.find(query)
.sort({ _id: -1 })
.limit(limit + 1)
.toArray();
if (repetitions.length === limit + 1) {
result.nextCursor = repetitions.pop()._id;
}
for (const repetition of repetitions) {
const event = this._composeEventWithRepetition(eventOriginal, repetition);
result.repetitions.push({
...event,
projectId: this.projectId,
});
}
const isLastPortion = result.nextCursor === null;
/**
* For last portion:
* add original event to the end of repetitions list
*/
if (isLastPortion) {
/**
* Get only 'repetitions' fields from event to fit Repetition scheme
* @type {EventRepetitionSchema}
*/
const firstRepetition = {
...eventOriginal,
originalTimestamp: eventOriginal.timestamp,
originalEventId: eventOriginal._id,
projectId: this.projectId,
};
result.repetitions.push(firstRepetition);
}
return result;
}
/**
* Returns certain repetition of the original event
*
* @param {String} repetitionId - id of Repetition to find
* @param {String} originalEventId - id of the original event
* @return {EventRepetitionSchema|null}
*/
async getEventRepetition(repetitionId, originalEventId) {
/**
* If originalEventId equals repetitionId than user wants to get first repetition which is original event
*/
if (repetitionId === originalEventId) {
const originalEvent = await this.eventsDataLoader.load(originalEventId);
/**
* All events have same type with originalEvent id
*/
originalEvent.originalEventId = originalEventId;
originalEvent.originalTimestamp = originalEvent.timestamp;
originalEvent.projectId = this.projectId;
return originalEvent || null;
}
/**
* Otherwise we need to get original event and repetition and merge them
*/
const repetition = await this.getCollection(this.TYPES.REPETITIONS)
.findOne({
_id: ObjectID(repetitionId),
});
const originalEvent = await this.eventsDataLoader.load(originalEventId);
/**
* If one of the ids are invalid (originalEvent or repetition not found) return null
*/
if (!originalEvent || !repetition) {
throw new Error(`Cant find event repetition for repetitionId: ${repetitionId} and originalEventId: ${originalEventId}`);
}
return this._composeEventWithRepetition(originalEvent, repetition);
}
/**
* Return last occurrence of event
* @param {string} eventId - id of event to find repetition
* @return {EventRepetitionSchema|null}
*/
async getEventLastRepetition(eventId) {
const repetitions = await this.getEventRepetitions(eventId, 1);
if (repetitions.length === 0) {
return null;
}
return repetitions.shift();
}
/**
* Get a release from corresponding to this event
*
* @param {string} eventId - id of event to get the release
* @returns {Release|null}
*/
async getEventRelease(eventId) {
const eventOriginal = await this.findById(eventId);
if (!eventOriginal || !eventOriginal.payload.release) {
return null;
}
const release = await mongo.databases.events.collection(this.TYPES.RELEASES).findOne({
release: eventOriginal.payload.release,
projectId: this.projectId.toString(),
});
return release;
}
/**
* Mark event as visited for passed user
*
* @param {string|ObjectId} eventId - id of the original event
* @param {string|ObjectId} userId - id of the user who is visiting the event
*
* @return {Promise<UpdateWriteOpResult>}
*/
async visitEvent(eventId, userId) {
const result = await this.getCollection(this.TYPES.EVENTS)
.updateOne(
{ _id: new ObjectID(eventId) },
{ $addToSet: { visitedBy: new ObjectID(userId) } }
);
if (result.matchedCount === 0) {
throw new Error(`Event not found for eventId: ${eventId}`);
}
return result;
}
/**
* Mark or unmark event as Resolved, Ignored or Starred
*
* @param {string|ObjectId} eventId - id of the original event to mark
* @param {string} mark - mark label
*
* @return {Promise<UpdateWriteOpResult>}
*/
async toggleEventMark(eventId, mark) {
const collection = this.getCollection(this.TYPES.EVENTS);
const event = await this.eventsDataLoader.load(eventId);
if (!event) {
throw new Error(`Event not found for eventId: ${eventId}`);
}
const query = { _id: new ObjectID(event._id) };
const markKey = `marks.${mark}`;
let update;
if (event.marks && event.marks[mark]) {
update = {
$unset: { [markKey]: '' },
};
} else {
update = {
$set: { [markKey]: Math.floor(Date.now() / 1000) },
};
}
return collection.updateOne(query, update);
}
/**
* Remove all project events
*
* @return {Promise<void>}
*/
async remove() {
/**
* Check if collection is existing
* Drop collection only when it's existing
*/
if (await this.isCollectionExists(this.TYPES.EVENTS)) {
await this.getCollection(this.TYPES.EVENTS).drop();
}
if (await this.isCollectionExists(this.TYPES.DAILY_EVENTS)) {
await this.getCollection(this.TYPES.DAILY_EVENTS).drop();
}
if (await this.isCollectionExists(this.TYPES.REPETITIONS)) {
await this.getCollection(this.TYPES.REPETITIONS).drop();
}
}
/**
* Update assignee to selected event
*
* @param {string} eventId - id of the original event to update
* @param {string} assignee - assignee id for this event
* @return {Promise<void>}
*/
async updateAssignee(eventId, assignee) {
const collection = this.getCollection(this.TYPES.EVENTS);
const query = { _id: new ObjectID(eventId) };
const update = {
$set: { assignee: assignee },
};
const result = await collection.updateOne(query, update);
if (result.updatedCount === 0) {
throw new Error(`Event not found for eventId: ${eventId}`);
}
return result;
}
/**
* Compose event with repetition
*
* @param {Event} event - event
* @param {Repetition|null} repetition - repetition null
* @returns {Event} event merged with repetition
*/
_composeEventWithRepetition(event, repetition) {
if (!repetition) {
return {
...event,
originalTimestamp: event.timestamp,
originalEventId: event._id,
projectId: this.projectId,
};
}
return {
...event,
_id: repetition._id,
originalTimestamp: event.timestamp,
originalEventId: event._id,
timestamp: repetition.timestamp,
payload: composeEventPayloadByRepetition(event.payload, repetition),
projectId: this.projectId,
};
}
}
module.exports = EventsFactory;