Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -273,17 +273,17 @@ describe('NotificationController', () => {



it('should throw error when notifications is null', async () => {
it('should throw error when notifications is null', async () => {
// Arrange - Setup query mock to return no items
const mockQueryResponse = {
Items: null // or undefined or []
Items: [] // Empty array instead of null
};

mockQuery.mockReturnValue({ promise: vi.fn().mockResolvedValue(mockQueryResponse) });

// Act & Assert
await expect(notificationService.getNotificationByUserId('nonexistent-user'))
.rejects.toThrow('Failed to retrieve notifications.');
const result = await notificationService.getNotificationByUserId('nonexistent-user');
expect(result).toEqual([]);
});

it('should create notification with valid data in the set table', async () => {
Expand Down
5 changes: 5 additions & 0 deletions backend/src/notifications/notification.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ export class NotificationController {
return await this.notificationService.getNotificationByNotificationId(notificationId);
}

@Get('/user/:userId/current')
async findCurrentByUser(@Param('userId') userId: string) {
return await this.notificationService.getCurrentNotificationsByUserId(userId);
}

// gets notifications by user id (sorted by most recent notifications first)
@Get('/user/:userId')
async findByUser(@Param('userId') userId: string) {
Expand Down
27 changes: 23 additions & 4 deletions backend/src/notifications/notification.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';
import * as AWS from 'aws-sdk';
import { Notification } from '../../../middle-layer/types/Notification';

Expand All @@ -7,6 +7,8 @@ export class NotificationService {

private dynamoDb = new AWS.DynamoDB.DocumentClient();
private ses = new AWS.SES({ region: process.env.AWS_REGION });
private readonly logger = new Logger(NotificationService.name);


// function to create a notification
// Should this have a check to prevent duplicate notifications?
Expand All @@ -25,6 +27,14 @@ export class NotificationService {
return notification;
}

async getCurrentNotificationsByUserId(userId: string): Promise<Notification[]> {
const notifactions = await this.getNotificationByUserId(userId);

const currentTime = new Date();

return notifactions.filter(notification => new Date(notification.alertTime) <= currentTime);
}


// function that returns array of notifications by user id (sorted by most recent notifications first)
async getNotificationByUserId(userId: string): Promise<Notification[]> {
Expand All @@ -33,8 +43,15 @@ export class NotificationService {
// ExpressionAttributeValues specifies the actual value of the key
// IndexName specifies our Global Secondary Index, which was created in the BCANNotifs table to
// allow for querying by userId, as it is not a primary/partition key
const notificationTableName = process.env.DYNAMODB_NOTIFICATION_TABLE_NAME;
this.logger.log(`Fetching notifications for userId: ${userId} from table: ${notificationTableName}`);

if (!notificationTableName) {
this.logger.error('DYNAMODB_NOTIFICATION_TABLE_NAME is not defined in environment variables');
throw new Error("Internal Server Error")
}
const params = {
TableName: process.env.DYNAMODB_NOTIFICATION_TABLE_NAME || 'TABLE_FAILURE',
TableName: notificationTableName,
IndexName: 'userId-alertTime-index',
KeyConditionExpression: 'userId = :userId',
ExpressionAttributeValues: {
Expand All @@ -47,14 +64,16 @@ export class NotificationService {


const data = await this.dynamoDb.query(params).promise();

// This is never hit, because no present userId throws an error
if (!data || !data.Items || data.Items.length == 0) {
throw new Error('No notifications with user id ' + userId + ' found.');
this.logger.warn(`No notifications found for userId: ${userId}`);
return [] as Notification[];
}

return data.Items as Notification[];
} catch (error) {
console.log(error)
this.logger.error(`Error retrieving notifications for userId: ${userId}`, error as string);
throw new Error('Failed to retrieve notifications.');
}
}
Expand Down
Loading