All files / src/services notification.service.ts

16.13% Statements 10/62
0% Branches 0/30
9.09% Functions 1/11
14.04% Lines 8/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1961x 1x   1x 1x       1x   62x     1x     62x                                                                                                                                                                                                                                                                                                                                                                      
import {bind, BindingScope, inject} from '@loopback/core';
import {DocumentClient} from 'aws-sdk/clients/dynamodb';
import {TFunction} from 'i18next';
import {v4 as uuidv4} from 'uuid';
import {I18NextBindings} from '../components/i18next';
import {AnyObject, RecipientNotification} from '../types';
 
@bind({scope: BindingScope.TRANSIENT})
export class NotificationService {
  docClient: DocumentClient;
  private _tableName = process.env.AWS_NOTIFICATION_TABLE;
 
  @inject(I18NextBindings.I18NEXT_TRANSLATION_FUNCTION)
  public t: TFunction;
 
  constructor() {
    this.docClient = new DocumentClient();
  }
 
  /**
   * Send bulk notifications to the user.
   * @param template The template
   * @param recipients The recipients.
   */
  async sendBulkNotifications(template: string, recipients: RecipientNotification[]) {
    if (!recipients?.length) {
      return;
    }
 
    const writeRequests: AnyObject[][] = [];
    const now = new Date().toISOString();
    let total = 0;
    for (const recipient of recipients) {
      if (!recipient.sub) {
        continue;
      }
 
      const index = Math.floor(total++ / 25);
      if (!writeRequests[index]) {
        writeRequests[index] = [];
      }
      writeRequests[index].push({
        PutRequest: {
          Item: {
            id: uuidv4(),
            cognitoId: recipient.sub,
            feedType: 'ALL',
            message: this.t(`${template}.title`, {
              lng: recipient.language,
              ...recipient.replacement_data,
            }),
            uri: recipient.replacement_data.link,
            createdAt: now,
            readStatus: 'false',
          },
        },
      });
    }
    return Promise.all(
      writeRequests.map(async (writeRequest: AnyObject[]) => {
        const params: DocumentClient.BatchWriteItemInput = {
          RequestItems: {
            [`${this._tableName}`]: writeRequest,
          },
        };
 
        try {
          return await this.docClient.batchWrite(params).promise();
        } catch (err) {
          console.log('Error when batchWrite: ', err);
        }
      }),
    );
  }
 
  /**
   */
  async getNotificationsByUser(cognitoId: string): Promise<AnyObject[]> {
    const params: DocumentClient.QueryInput = {
      TableName: `${this._tableName}`,
      IndexName: 'cognitoId-createdAt-index',
      KeyConditionExpression: 'cognitoId = :cid',
      ExpressionAttributeValues: {':cid': cognitoId},
      ScanIndexForward: false,
    };
 
    try {
      const result = await this.docClient.query(params).promise();
      return result.Items ?? [];
    } catch (err) {
      console.log('Error when getNotificationsByUser:', err);
      return [];
    }
  }
 
  /**
   */
  async countUnread(cognitoId: string): Promise<number> {
    const params: DocumentClient.QueryInput = {
      TableName: `${this._tableName}`,
      IndexName: 'cognitoId-createdAt-index',
      KeyConditionExpression: 'cognitoId = :cid',
      FilterExpression: 'readStatus = :unread',
      ExpressionAttributeValues: {
        ':cid': cognitoId,
        ':unread': 'false',
      },
      Select: 'COUNT',
    };
 
    try {
      const result = await this.docClient.query(params).promise();
      return result.Count ?? 0;
    } catch (err) {
      console.log('Error when countUnread:', err);
      return 0;
    }
  }
 
  /**
   */
  async markAsRead(id: string): Promise<void> {
    const params: DocumentClient.UpdateItemInput = {
      TableName: `${this._tableName}`,
      Key: {id},
      UpdateExpression: 'SET readStatus = :read',
      ExpressionAttributeValues: {':read': 'true'},
    };
 
    try {
      await this.docClient.update(params).promise();
    } catch (err) {
      console.log('Error when markAsRead:', err);
    }
  }
 
  /**
   */
  async markAllAsRead(cognitoId: string): Promise<void> {
    const notifications = await this.getNotificationsByUser(cognitoId);
    const unread = notifications.filter(n => n.readStatus === 'false');
 
    if (!unread.length) return;
    await Promise.all(unread.map(n => this.markAsRead(n.id)));
  }
 
  async getNotificationsByUserAndPeriod(cognitoId: string, start: Date, end: Date, limit = 20): Promise<AnyObject[]> {
    const params: DocumentClient.QueryInput = {
      TableName: `${this._tableName}`,
      IndexName: 'cognitoId-createdAt-index',
      KeyConditionExpression: 'cognitoId = :cid AND createdAt BETWEEN :start AND :end',
      ExpressionAttributeValues: {
        ':cid': cognitoId,
        ':start': start.toISOString(),
        ':end': end.toISOString(),
      },
      ScanIndexForward: false,
      Limit: limit,
    };
 
    try {
      const result = await this.docClient.query(params).promise();
      return result.Items ?? [];
    } catch (err) {
      console.log('Error when getNotificationsByUserAndPeriod:', err);
      return [];
    }
  }
 
  async getGlobalNotificationsByPeriod(start: Date, end: Date, limit = 20): Promise<AnyObject[]> {
    const params: DocumentClient.QueryInput = {
      TableName: `${this._tableName}`,
      IndexName: 'GlobalCreatedAtIndex',
 
      KeyConditionExpression: 'feedType = :feedType AND createdAt BETWEEN :start AND :end',
 
      ExpressionAttributeValues: {
        ':feedType': 'ALL',
        ':start': start.toISOString(),
        ':end': end.toISOString(),
      },
 
      ScanIndexForward: false,
      Limit: limit,
    };
 
    try {
      const result = await this.docClient.query(params).promise();
      return result.Items ?? [];
    } catch (err) {
      console.log('Error when getGlobalNotificationsByPeriod:', err);
      return [];
    }
  }
}