• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

GrottoCenter / grottocenter-api / 26279638452

22 May 2026 09:20AM UTC coverage: 86.85% (-0.2%) from 87.052%
26279638452

Pull #1566

github

dawoldo
fix(1451): handle markAsRead errors gracefully and improve conversation test cleanup
Pull Request #1566: 1451 private messaging

3346 of 4000 branches covered (83.65%)

Branch coverage included in aggregate %.

206 of 247 new or added lines in 16 files covered. (83.4%)

3 existing lines in 1 file now uncovered.

6772 of 7650 relevant lines covered (88.52%)

55.05 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.25
/api/services/NotificationService.js
1
const NameService = require('./NameService');
8✔
2
const CommonService = require('./CommonService');
8✔
3
const LanguageService = require('./LanguageService');
8✔
4

5
const NOTIFICATION_ENTITIES = {
8✔
6
  CAVE: 'cave',
7
  COMMENT: 'comment',
8
  DESCRIPTION: 'description',
9
  DOCUMENT: 'document',
10
  ENTRANCE: 'entrance',
11
  HISTORY: 'history',
12
  LOCATION: 'location',
13
  MASSIF: 'massif',
14
  ORGANIZATION: 'organization',
15
  RIGGING: 'rigging',
16
};
17

18
const NOTIFICATION_TYPES = {
8✔
19
  CREATE: 'CREATE',
20
  DELETE: 'DELETE',
21
  PERMANENT_DELETE: 'PERMANENT_DELETE',
22
  UPDATE: 'UPDATE',
23
  VALIDATE: 'VALIDATE',
24
  RESTORE: 'RESTORE',
25
  REJECT: 'REJECT',
26
};
27

28
async function removeOlderNotifications() {
29
  const query = `DELETE
×
30
                 FROM t_notification
31
                 WHERE date_inscription < current_timestamp - interval '2 month';`;
32
  await CommonService.query(query);
×
33
}
34

35
const safeGetPropId = (prop, data) => {
8✔
36
  if (data && data[prop]) {
1,905✔
37
    if (data[prop] instanceof Object) {
554✔
38
      return data[prop].id;
185✔
39
    }
40
    return data[prop];
369✔
41
  }
42
  return undefined;
1,351✔
43
};
44

45
const sendNotificationEmail = async (
8✔
46
  entity,
47
  notificationType,
48
  notificationEntity,
49
  user
50
) => {
51
  // Resolve the recipient's preferred locale
52
  const locale = await LanguageService.getLocale(user.language);
296✔
53

54
  // Get entity name (handle all cases)
55
  const getEntityName = (entityData) => {
296✔
56
    if (entityData.name) return entityData.name;
296✔
57
    if (entityData.names) return entityData.names[0]?.name;
31✔
58
    if (entityData.title) return entityData.title;
30✔
59
    if (entityData.titles) return entityData.titles[0]?.text;
16✔
60
    if (entityData.body) return `${entityData.body.slice(0, 50)}...`;
15✔
61
    if (entityData.descriptions) return entityData.descriptions[0].title;
14✔
62
    return '';
13✔
63
  };
64

65
  const entityName = getEntityName(entity);
296✔
66

67
  // Format action verb
68
  const actionVerbMap = {
296✔
69
    [NOTIFICATION_TYPES.CREATE]: 'created',
70
    [NOTIFICATION_TYPES.DELETE]: 'deleted',
71
    [NOTIFICATION_TYPES.PERMANENT_DELETE]: 'permanently deleted',
72
    [NOTIFICATION_TYPES.UPDATE]: 'updated',
73
    [NOTIFICATION_TYPES.VALIDATE]: 'validated',
74
    [NOTIFICATION_TYPES.RESTORE]: 'restored',
75
    [NOTIFICATION_TYPES.REJECT]: 'rejected',
76
  };
77

78
  const actionVerb = actionVerbMap[notificationType];
296✔
79
  if (!actionVerb) {
296✔
80
    throw Error(`Unknown notification type: ${notificationType}`);
1✔
81
  }
82

83
  // Format entity Link
84
  const baseUrl = `${sails.config.custom.baseUrl}/ui/`;
295✔
85
  const relatedCaveId = safeGetPropId('cave', entity);
295✔
86
  const relatedEntranceId = safeGetPropId('entrance', entity);
295✔
87
  const relatedMassifId = safeGetPropId('massif', entity);
295✔
88

89
  const getRelatedEntityLink = () => {
295✔
90
    if (relatedCaveId) return `caves/${relatedCaveId}`;
22✔
91
    if (relatedEntranceId) return `entrances/${relatedEntranceId}`;
20✔
92
    if (relatedMassifId) return `massifs/${relatedMassifId}`;
5✔
93
    return null;
4✔
94
  };
95

96
  const directLinkEntities = {
295✔
97
    [NOTIFICATION_ENTITIES.CAVE]: `caves/${entity.id}`,
98
    [NOTIFICATION_ENTITIES.DOCUMENT]: `documents/${entity.id}`,
99
    [NOTIFICATION_ENTITIES.ENTRANCE]: `entrances/${entity.id}`,
100
    [NOTIFICATION_ENTITIES.MASSIF]: `massifs/${entity.id}`,
101
    [NOTIFICATION_ENTITIES.ORGANIZATION]: `organizations/${entity.id}`,
102
  };
103

104
  let entityLink;
105
  if (directLinkEntities[notificationEntity]) {
295✔
106
    entityLink = baseUrl + directLinkEntities[notificationEntity];
273✔
107
  } else {
108
    const relatedLink = getRelatedEntityLink();
22✔
109
    if (!relatedLink) {
22✔
110
      const entityTypeName = notificationEntity.toLowerCase();
4✔
111
      let requiredEntities;
112
      if (notificationEntity === NOTIFICATION_ENTITIES.DESCRIPTION) {
4✔
113
        requiredEntities = 'cave, entrance or massif';
1✔
114
      } else if (notificationEntity === NOTIFICATION_ENTITIES.LOCATION) {
3✔
115
        requiredEntities = 'entrance';
1✔
116
      } else {
117
        requiredEntities = 'cave or entrance';
2✔
118
      }
119
      throw Error(
4✔
120
        `Can't find related entity (${requiredEntities}) of the ${entityTypeName} with id ${entity.id}`
121
      );
122
    }
123
    entityLink = baseUrl + relatedLink;
18✔
124
  }
125

126
  await sails.helpers.sendEmail
291✔
127
    .with({
128
      allowResponse: false,
129
      emailSubject: 'Notification',
130
      locale,
131
      recipientEmail: user.mail,
132
      viewName: 'notification',
133
      viewValues: {
134
        actionVerb,
135
        entityLink,
136
        entityName,
137
        entityType: notificationEntity,
138
        recipientName: user.nickname,
139
        subscriptionName: user.subscriptionName,
140
        subscriptionType: user.subscriptionType,
141
        isAuthorNotification: user.isAuthorNotification || false,
390✔
142
        validationComment: user.validationComment || null,
419✔
143
      },
144
    })
145
    .intercept('sendSESEmailError', () => {
146
      sails.log.error(
×
147
        `The email service has encountered an error while trying to notify user ${user.nickname} (id=${user.id}).`
148
      );
149
      return false;
×
150
    });
151
};
152

153
const getCountryMassifAndRegionSubscribers = async (
8✔
154
  entityCountryId,
155
  entityMassifIds,
156
  entityRegionId
157
) => {
158
  const countrySubscribers = [];
146✔
159
  const massifsSubscribers = [];
146✔
160
  const regionSubscribers = [];
146✔
161
  if (entityCountryId) {
146✔
162
    const country =
163
      await TCountry.findOne(entityCountryId).populate('subscribedCavers');
3✔
164
    if (country) {
3!
165
      countrySubscribers.push(
3✔
166
        ...country.subscribedCavers.map((caver) => ({
3✔
167
          ...caver,
168
          subscriptionName: country.nativeName,
169
          subscriptionType: 'country',
170
        }))
171
      );
172
    }
173
  }
174
  if (entityMassifIds) {
146!
175
    await Promise.all(
146✔
176
      entityMassifIds.map(async (massifId) => {
177
        const massif =
178
          await TMassif.findOne(massifId).populate('subscribedCavers');
77✔
179
        if (massif) {
77✔
180
          await NameService.setNames([massif], 'massif');
73✔
181
          massifsSubscribers.push(
73✔
182
            ...massif.subscribedCavers.map((caver) => ({
63✔
183
              ...caver,
184
              subscriptionType: 'massif',
185
              subscriptionName: massif.names[0]?.name,
186
            }))
187
          );
188
        }
189
      })
190
    );
191
  }
192
  if (entityRegionId) {
146✔
193
    const region =
194
      await TISO31662.findOne(entityRegionId).populate('subscribedCavers');
3✔
195
    if (region) {
3!
196
      regionSubscribers.push(
3✔
197
        ...region.subscribedCavers.map((caver) => ({
3✔
198
          ...caver,
199
          subscriptionName: region.name,
200
          subscriptionType: 'region',
201
        }))
202
      );
203
    }
204
  }
205
  return { countrySubscribers, massifsSubscribers, regionSubscribers };
146✔
206
};
207

208
module.exports = {
8✔
209
  NOTIFICATION_ENTITIES,
210
  notifyMessageRecipient: async (senderId, conversationId) => {
211
    try {
9✔
212
      const sender = await TCaver.findOne({ id: senderId });
9✔
213
      if (!sender) return;
9!
214
      const query = `SELECT id_caver FROM j_participant WHERE id_conversation = $1 AND id_caver != $2`;
9✔
215
      const result = await CommonService.query(query, [
9✔
216
        conversationId,
217
        senderId,
218
      ]);
219
      if (result.rows.length === 0) return;
9!
220
      const row = result.rows[0];
9✔
221
      const recipient = await TCaver.findOne({ id: row.id_caver });
9✔
222
      if (!recipient || !recipient.sendMessageNotificationByEmail) return;
9✔
223
      const locale = await LanguageService.getLocale(recipient.language);
7✔
224
      const conversationLink = `${sails.config.custom.baseUrl}/ui/messages/${conversationId}`;
7✔
225
      await sails.helpers.sendEmail
7✔
226
        .with({
227
          allowResponse: false,
228
          emailSubject: 'New Message',
229
          locale,
230
          recipientEmail: recipient.mail,
231
          viewName: 'new-message',
232
          viewValues: {
233
            senderNickname: sender.nickname,
234
            conversationLink,
235
            recipientName: recipient.nickname,
236
          },
237
        })
238
        .intercept('sendSESEmailError', () => {
NEW
239
          sails.log.error(
×
240
            `The email service error notifying user ${recipient.nickname}.`
241
          );
NEW
242
          return false;
×
243
        });
244
    } catch (error) {
NEW
245
      sails.log.error(
×
246
        `An error occurred in notifyMessageRecipient: ${error.message}`
247
      );
248
    }
249
  },
250
  NOTIFICATION_TYPES,
251
  ...(process.env.NODE_ENV === 'test' ? { sendNotificationEmail } : undefined),
8!
252

253
  /**
254
   *
255
   * @param {*} entity
256
   * @param {Number} notifierId
257
   * @param {NOTIFICATION_TYPES} notificationType
258
   * @param {NOTIFICATION_ENTITIES} notificationEntity
259
   * @return {Boolean} true if everything went well, else false
260
   */
261
  notifySubscribers: async (
262
    entity,
263
    notifierId,
264
    notificationType,
265
    notificationEntity
266
  ) => {
267
    // Had to require in the function to avoid a circular dependency with notifySubscribers() in CaveService.createCave()
268
    // eslint-disable-next-line global-require
269
    const CaveService = require('./CaveService');
157✔
270

271
    // Check params and silently fail to avoid sending an error to the client
272
    if (!Object.values(NOTIFICATION_ENTITIES).includes(notificationEntity)) {
157✔
273
      throw new Error(`Invalid notification entity: ${notificationEntity}`);
1✔
274
    }
275
    if (!Object.values(NOTIFICATION_TYPES).includes(notificationType)) {
156✔
276
      throw new Error(`Invalid notification type: ${notificationType}`);
1✔
277
    }
278
    if (!notifierId) {
155✔
279
      throw new Error(`Missing notifier id`);
1✔
280
    }
281

282
    try {
154✔
283
      // For the populateEntities() method, must use "grotto" instead of "organization"
284
      const entityKey =
285
        notificationEntity === NOTIFICATION_ENTITIES.ORGANIZATION
154✔
286
          ? 'grotto'
287
          : notificationEntity;
288

289
      // Format notification and populate entity
290
      const notification = await module.exports.populateEntities({
154✔
291
        dateInscription: new Date(),
292
        notificationType: (
293
          await TNotificationType.findOne({
294
            name: notificationType,
295
          })
296
        ).id,
297
        notifier: notifierId,
298
        [entityKey]: entity,
299
      });
300

301
      const populatedEntity = notification[entityKey];
154✔
302

303
      const caveId = safeGetPropId('cave', populatedEntity);
154✔
304
      const entranceId = safeGetPropId('entrance', populatedEntity);
154✔
305
      const massifId = safeGetPropId('massif', populatedEntity);
154✔
306

307
      const getMassifIdsFromCave = async (id) =>
154✔
308
        (await CaveService.getMassifs(id)).map((m) => m.id);
76✔
309
      const getCountryId = (id) => safeGetPropId('country', id);
154✔
310
      const getRegionId = (entityData) => entityData?.iso_3166_2;
154✔
311

312
      const getCountryFromCaveEntrances = (cave) => {
154✔
313
        if (cave?.entrances?.length > 0) {
16✔
314
          return getCountryId(cave.entrances[0]);
5✔
315
        }
316
        return null;
11✔
317
      };
318

319
      const resolveLocationFromCaveOrEntrance = async (
154✔
320
        relatedCaveId,
321
        relatedEntranceId,
322
        entityData
323
      ) => {
324
        if (relatedCaveId) {
65✔
325
          return {
3✔
326
            countryId: getCountryFromCaveEntrances(entityData.cave),
327
            massifIds: await getMassifIdsFromCave(relatedCaveId),
328
            regionId: entityData.cave?.entrances?.[0]
3!
329
              ? getRegionId(entityData.cave.entrances[0])
330
              : null,
331
          };
332
        }
333
        if (relatedEntranceId) {
62✔
334
          return {
19✔
335
            countryId: getCountryId(entityData.entrance),
336
            massifIds: await getMassifIdsFromCave(
337
              safeGetPropId('cave', entityData.entrance)
338
            ),
339
            regionId: getRegionId(entityData.entrance),
340
          };
341
        }
342
        return { countryId: null, massifIds: [], regionId: null };
43✔
343
      };
344

345
      // Entity-specific location resolution
346
      const entityResolvers = {
154✔
347
        [NOTIFICATION_ENTITIES.CAVE]: async () => ({
13✔
348
          countryId: getCountryFromCaveEntrances(populatedEntity),
349
          massifIds: await getMassifIdsFromCave(populatedEntity.id),
350
          regionId: populatedEntity?.entrances?.[0]
13✔
351
            ? getRegionId(populatedEntity.entrances[0])
352
            : null,
353
        }),
354

355
        [NOTIFICATION_ENTITIES.ENTRANCE]: async () => ({
38✔
356
          countryId: getCountryId(populatedEntity),
357
          massifIds: populatedEntity?.cave
38✔
358
            ? await getMassifIdsFromCave(safeGetPropId('cave', populatedEntity))
359
            : [],
360
          regionId: getRegionId(populatedEntity),
361
        }),
362

363
        [NOTIFICATION_ENTITIES.MASSIF]: async () => ({
11✔
364
          countryId: null,
365
          massifIds: [populatedEntity.id],
366
          regionId: null,
367
        }),
368

369
        [NOTIFICATION_ENTITIES.ORGANIZATION]: async () => ({
16✔
370
          countryId: getCountryId(populatedEntity),
371
          massifIds: [],
372
          regionId: getRegionId(populatedEntity),
373
        }),
374

375
        [NOTIFICATION_ENTITIES.LOCATION]: async () => {
376
          if (!entranceId)
11✔
377
            throw new Error(`Can't retrieve related entrance id.`);
2✔
378
          return {
9✔
379
            countryId: getCountryId(populatedEntity.entrance),
380
            massifIds: await getMassifIdsFromCave(
381
              safeGetPropId('cave', populatedEntity.entrance)
382
            ),
383
            regionId: getRegionId(populatedEntity.entrance),
384
          };
385
        },
386
      };
387

388
      // Entities that can relate to cave, entrance, or massif
389
      const multiRelationEntities = [
154✔
390
        NOTIFICATION_ENTITIES.COMMENT,
391
        NOTIFICATION_ENTITIES.DESCRIPTION,
392
        NOTIFICATION_ENTITIES.HISTORY,
393
        NOTIFICATION_ENTITIES.RIGGING,
394
      ];
395

396
      // Find massifs and country concerned about the notification
397
      let result;
398
      if (entityResolvers[notificationEntity]) {
154✔
399
        result = await entityResolvers[notificationEntity]();
89✔
400
      } else if (multiRelationEntities.includes(notificationEntity)) {
65✔
401
        result = await resolveLocationFromCaveOrEntrance(
30✔
402
          caveId,
403
          entranceId,
404
          populatedEntity
405
        );
406

407
        // Handle massif-only case for description and document
408
        if (!result.countryId && !result.massifIds.length && massifId) {
30!
409
          result.massifIds = [safeGetPropId('massif', populatedEntity)];
×
410
        }
411

412
        // Require cave or entrance for most entities
413
        if (
30✔
414
          !caveId &&
65✔
415
          !entranceId &&
416
          ![
417
            NOTIFICATION_ENTITIES.DESCRIPTION,
418
            NOTIFICATION_ENTITIES.DOCUMENT,
419
          ].includes(notificationEntity)
420
        ) {
421
          throw new Error(`Can't retrieve related cave or entrance id.`);
6✔
422
        }
423
      } else if (notificationEntity === NOTIFICATION_ENTITIES.DOCUMENT) {
35!
424
        result = await resolveLocationFromCaveOrEntrance(
35✔
425
          caveId,
426
          entranceId,
427
          populatedEntity
428
        );
429
        if (!result.countryId && !result.massifIds.length && massifId) {
35!
430
          result.massifIds = [safeGetPropId('massif', populatedEntity)];
×
431
        }
432
      } else {
433
        throw new Error(
×
434
          `Can't find what to do with the following notification entity value: ${notificationEntity}`
435
        );
436
      }
437

438
      const entityCountryId = result.countryId;
146✔
439
      const entityMassifIds = result.massifIds;
146✔
440
      const entityRegionId = result.regionId;
146✔
441

442
      // Find subscribers to the entity.
443
      const { countrySubscribers, massifsSubscribers, regionSubscribers } =
444
        await getCountryMassifAndRegionSubscribers(
146✔
445
          entityCountryId,
446
          entityMassifIds,
447
          entityRegionId
448
        );
449
      // Consolidate subscribers by user ID and combine subscription types
450
      const subscriberMap = new Map();
146✔
451

452
      const addSubscribers = (subscribers) => {
146✔
453
        subscribers
438✔
454
          .filter((u) => u.id !== notifierId)
69✔
455
          .forEach((user) => {
456
            if (subscriberMap.has(user.id)) {
69✔
457
              const existing = subscriberMap.get(user.id);
2✔
458
              existing.subscriptionNames.push(user.subscriptionName);
2✔
459
              existing.subscriptionTypes.push(user.subscriptionType);
2✔
460
            } else {
461
              subscriberMap.set(user.id, {
67✔
462
                ...user,
463
                subscriptionNames: [user.subscriptionName],
464
                subscriptionTypes: [user.subscriptionType],
465
              });
466
            }
467
          });
468
      };
469

470
      addSubscribers(countrySubscribers);
146✔
471
      addSubscribers(massifsSubscribers);
146✔
472
      addSubscribers(regionSubscribers);
146✔
473

474
      const uniqueUsers = Array.from(subscriberMap.values()).map((user) => ({
146✔
475
        ...user,
476
        subscriptionName: user.subscriptionNames.join(' and '),
477
        subscriptionType: user.subscriptionTypes.join(', '),
478
      }));
479

480
      // Create notifications & optionally send email
481
      const res = await Promise.all(
146✔
482
        uniqueUsers.map(async (user) => {
483
          try {
67✔
484
            await TNotification.create({
67✔
485
              ...notification,
486
              notified: user.id,
487
              [entityKey]: notification[entityKey].id, // id only for the DB storage
488
            });
489
          } catch (e) {
490
            sails.log.error(
×
491
              `An error occured when trying to create a notification: ${e.message}`
492
            );
493
            return false;
×
494
          }
495

496
          if (user.sendNotificationByEmail) {
67!
497
            await sendNotificationEmail(
×
498
              populatedEntity,
499
              notificationType,
500
              notificationEntity,
501
              user
502
            );
503
          }
504
          return true;
67✔
505
        })
506
      );
507

508
      // 5% chance to also remove older notifications
509
      if (process.env.NODE_ENV !== 'test' && Math.random() < 0.05) {
146!
510
        try {
×
511
          await removeOlderNotifications();
×
512
        } catch (cleanupError) {
513
          sails.log.error(
×
514
            `Error during notification cleanup: ${cleanupError.message}`
515
          );
516
        }
517
      }
518

519
      return res;
146✔
520
    } catch (error) {
521
      // Fail silently to avoid sending an error to the user
522
      sails.log.error(
8✔
523
        `An error occurred when trying to notify subscribers: ${error.message} ${error.stack}`
524
      );
525
      return false;
8✔
526
    }
527
  },
528

529
  /**
530
   * Create an in-app notification for the document author and optionally send an email.
531
   *
532
   * @param {Object}  document         - Populated TDocument (must have .author)
533
   * @param {Number}  moderatorId      - ID of the moderator who made the decision
534
   * @param {String}  notificationType - NOTIFICATION_TYPES.VALIDATE or NOTIFICATION_TYPES.REJECT
535
   * @param {String|null} validationComment - Moderator's comment (required for REJECT)
536
   * @returns {Boolean} true on success, false on silent failure
537
   */
538
  notifyAuthor: async (
539
    document,
540
    moderatorId,
541
    notificationType,
542
    validationComment
543
  ) => {
544
    const authorId = safeGetPropId('author', document);
323✔
545
    if (!authorId) {
323✔
546
      sails.log.debug(
1✔
547
        `notifyAuthor: document ${document.id} has no author, skipping notification`
548
      );
549
      return true;
1✔
550
    }
551
    if (authorId === moderatorId) {
322✔
552
      return true;
103✔
553
    }
554

555
    if (!Object.values(NOTIFICATION_TYPES).includes(notificationType)) {
219!
556
      throw new Error(`Invalid notification type: ${notificationType}`);
×
557
    }
558

559
    try {
219✔
560
      const notificationTypeRecord = await TNotificationType.findOne({
219✔
561
        name: notificationType,
562
      });
563

564
      if (!notificationTypeRecord) {
219!
565
        throw new Error(
×
566
          `Notification type '${notificationType}' not found in DB — migration may not have run`
567
        );
568
      }
569

570
      await TNotification.create({
219✔
571
        dateInscription: new Date(),
572
        notificationType: notificationTypeRecord.id,
573
        notifier: moderatorId,
574
        notified: authorId,
575
        document: document.id,
576
      });
577

578
      const author = await TCaver.findOne(authorId);
219✔
579

580
      if (author && author.sendNotificationByEmail) {
219✔
581
        await sendNotificationEmail(
52✔
582
          document,
583
          notificationType,
584
          NOTIFICATION_ENTITIES.DOCUMENT,
585
          {
586
            ...author,
587
            isAuthorNotification: true,
588
            validationComment,
589
          }
590
        );
591
      }
592

593
      return true;
219✔
594
    } catch (error) {
595
      sails.log.error(
×
596
        `An error occurred when trying to notify the document author: ${error.message} ${error.stack}`
597
      );
598
      return false;
×
599
    }
600
  },
601

602
  populateEntities: async (notification) => {
603
    const populatedNotification = notification;
204✔
604
    if (populatedNotification.cave) {
204✔
605
      await NameService.setNames([populatedNotification.cave], 'cave');
15✔
606
    }
607
    if (populatedNotification.comment) {
204✔
608
      populatedNotification.comment = await TComment.findOne(
11✔
609
        safeGetPropId('comment', notification)
610
      )
611
        .populate('cave')
612
        .populate('entrance');
613
    }
614
    if (populatedNotification.description) {
204✔
615
      populatedNotification.description = await TDescription.findOne(
10✔
616
        safeGetPropId('description', notification)
617
      )
618
        .populate('cave')
619
        .populate('document')
620
        .populate('entrance')
621
        .populate('massif');
622
    }
623
    if (populatedNotification.document) {
204✔
624
      // Had to require in the function to avoid a circular dependency with notifySubscribers() in DocumentService.createDocument()
625
      // eslint-disable-next-line global-require
626
      const DocumentService = require('./DocumentService');
42✔
627
      const populatedDocuments = await DocumentService.getDocuments([
42✔
628
        safeGetPropId('document', notification),
629
      ]);
630
      populatedNotification.document = populatedDocuments[0];
42✔
631
    }
632
    if (populatedNotification.entrance) {
204✔
633
      await NameService.setNames([populatedNotification.entrance], 'entrance');
53✔
634
    }
635
    if (populatedNotification.grotto) {
204✔
636
      await NameService.setNames([populatedNotification.grotto], 'grotto');
16✔
637
    }
638
    if (populatedNotification.history) {
204✔
639
      populatedNotification.history = await THistory.findOne(
7✔
640
        safeGetPropId('history', notification)
641
      )
642
        .populate('cave')
643
        .populate('entrance');
644
    }
645
    if (populatedNotification.location) {
204✔
646
      populatedNotification.location = await TLocation.findOne(
12✔
647
        safeGetPropId('location', notification)
648
      ).populate('entrance');
649
    }
650
    if (populatedNotification.massif) {
204✔
651
      await NameService.setNames([populatedNotification.massif], 'massif');
11✔
652
    }
653
    if (populatedNotification.rigging) {
204✔
654
      populatedNotification.rigging = await TRigging.findOne(
6✔
655
        safeGetPropId('rigging', notification)
656
      )
657
        .populate('entrance')
658
        .populate('cave');
659
    }
660
    return populatedNotification;
204✔
661
  },
662
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc