@@ -7,9 +7,36 @@ module.exports = fp(async function (app, _opts) {
77 * @param {string } type the type of the notification
88 * @param {Object } data meta data for the notification - specific to the type
99 * @param {string } reference a key that can be used to lookup this notification, for example: `invite:HASHID`
10- *
10+ * @param {Object } [options]
11+ * @param {boolean } [options.upsert] if true, updates the existing notification with the same reference & adds/increments `data.meta.counter`
12+ * @param {boolean } [options.supersede] if true, marks existing notification (with the same reference) as read & adds a new one
1113 */
12- async function send ( user , type , data , reference = null ) {
14+ async function send ( user , type , data , reference = null , options = null ) {
15+ if ( reference && options && typeof options === 'object' ) {
16+ if ( options . upsert ) {
17+ const existing = await app . db . models . Notification . byReference ( reference , user )
18+ if ( existing && ! existing . read ) {
19+ const updatedData = Object . assign ( { } , existing . data , data )
20+ if ( ! updatedData . meta || typeof updatedData . meta !== 'object' ) {
21+ updatedData . meta = { }
22+ }
23+ if ( typeof updatedData . meta . counter === 'number' ) {
24+ updatedData . meta . counter += 1
25+ } else {
26+ updatedData . meta . counter = 2 // if notification already exists, then this is the 2nd occurrence!
27+ }
28+ await existing . update ( { data : updatedData } )
29+ return existing
30+ }
31+ } else if ( options . supersede ) {
32+ const existing = await app . db . models . Notification . byReference ( reference , user )
33+ if ( existing && ! existing . read ) {
34+ existing . read = true
35+ await existing . save ( )
36+ }
37+ }
38+ }
39+
1340 return app . db . models . Notification . create ( {
1441 UserId : user . id ,
1542 type,
0 commit comments