From 94e477ab9d736d0bae1d3ef73e867091d78df25d Mon Sep 17 00:00:00 2001 From: Mohammad Ranjbar Z Date: Wed, 24 Aug 2022 16:35:22 +0430 Subject: [PATCH 1/2] Refactor some functions --- src/controllers/v1/notificationsController.ts | 20 ++++++---- src/middlewares/authentication.ts | 33 ++-------------- src/repositories/notificationRepository.ts | 38 +++++++++---------- .../notificationTypeRepository.ts | 9 ++--- src/routes/v1/notificationSettingsRouter.ts | 6 +-- src/utils/errorMessages.ts | 4 +- src/utils/validators/segmentValidators.ts | 6 +-- 7 files changed, 44 insertions(+), 72 deletions(-) diff --git a/src/controllers/v1/notificationsController.ts b/src/controllers/v1/notificationsController.ts index eb506e3..2d8486c 100644 --- a/src/controllers/v1/notificationsController.ts +++ b/src/controllers/v1/notificationsController.ts @@ -57,11 +57,15 @@ export class NotificationsController { ): Promise { const { microService } = params; try { - const notificationType = await getNotificationTypeByEventName(body.eventName); + const notificationType = await getNotificationTypeByEventName( + body.eventName, + ); - if (!notificationType) throw new Error(errorMessages.INVALID_NOTIFICATION_TYPE); + if (!notificationType) + throw new Error(errorMessages.INVALID_NOTIFICATION_TYPE); - const schemaValidator = SCHEMA_VALIDATORS[notificationType.schemaValidator as string]; + const schemaValidator = + SCHEMA_VALIDATORS[notificationType.schemaValidator as string]; validateWithJoiSchema(body.data, schemaValidator); // TODO insert notification in DB @@ -148,12 +152,15 @@ export class NotificationsController { ): Promise { try { const user = params.user; - const notification = await markNotificationsAsRead( + const [notification] = await markNotificationsAsRead( [Number(notificationId)], user.id, ); + if (!notification) { + throw new Error(errorMessages.NOTIFICATION_NOT_FOUND); + } return { - notification: notification.raw[0], + notification, }; } catch (e) { logger.error('readNotification() error', e); @@ -174,9 +181,8 @@ export class NotificationsController { try { // in case mark as read all is limited per category await markNotificationGroupAsRead(user, params.category); - const notificationCounts = await countUnreadNotifications(user); - return notificationCounts; + return countUnreadNotifications(user); } catch (e) { logger.error('readNotification() error', e); throw e; diff --git a/src/middlewares/authentication.ts b/src/middlewares/authentication.ts index ee32cdd..08f51eb 100644 --- a/src/middlewares/authentication.ts +++ b/src/middlewares/authentication.ts @@ -73,28 +73,6 @@ export const authenticateThirdPartyServiceToken = async ( } }; -export const authenticateUser = async ( - req: Request, - res: Response, - next: NextFunction, -) => { - try { - const authorization = req.headers.authorization as string; - // TODO check with Authentication micro service - res.locals.user = { - userIdInGiveth: '', - userIdInTrace: '', - walletAddress: '', - email: '', - }; - res.locals.microservice = ''; - next(); - } catch (e) { - console.log('authenticateThirdPartyBasicAuth error', e); - next(e); - } -}; - export const validateAuthMicroserviceJwt = async ( req: Request, res: Response, @@ -118,14 +96,9 @@ export const validateAuthMicroserviceJwt = async ( const userAddress = result.data.publicAddress.toLowerCase(); - let user = await findUserByWalletAddress(userAddress); - - if (!user) { - user = await createNewUserAddress(userAddress); - } - - res.locals.user = user; - + res.locals.user = + (await findUserByWalletAddress(userAddress)) || + (await createNewUserAddress(userAddress)); next(); } catch (e) { console.log('authenticateThirdPartyBasicAuth error', e); diff --git a/src/repositories/notificationRepository.ts b/src/repositories/notificationRepository.ts index f032fd5..633564b 100644 --- a/src/repositories/notificationRepository.ts +++ b/src/repositories/notificationRepository.ts @@ -5,14 +5,15 @@ import { Notification } from '../entities/notification'; import { errorMessages } from '../utils/errorMessages'; import { query } from 'express'; import { NOTIFICATION_CATEGORY } from '../types/general'; +import { CountUnreadNotificationsResponse } from '../types/requestResponses'; export const markNotificationGroupAsRead = async ( user: UserAddress, category?: string, -) => { +): Promise => { let query = Notification.createQueryBuilder('notification') - .select('notification.id') .innerJoinAndSelect('notification."notificationType"', 'notificationType') + .update(Notification, { isRead: true }) .where('notification."userAddressId" = :userAddressId', { userAddressId: user.id, }) @@ -23,19 +24,15 @@ export const markNotificationGroupAsRead = async ( category: category, }); } - const notifications = await query.getMany(); - - const notificationsIds = notifications.map(notification => notification.id); - const updateQuery = await markNotificationsAsRead(notificationsIds); - - return updateQuery.raw; + await query.execute(); }; // returns raw data as array always export const markNotificationsAsRead = async ( ids: number[], userAddressId?: number, -) => { +): Promise => { + // TODO as I changed markNotificationGroupAsRead, we should change this function to just get one id and update that notificaiton let updateQuery = Notification.createQueryBuilder('notification') .update(Notification, { isRead: true }) .where('notification.id IN (:...ids)'); @@ -47,30 +44,33 @@ export const markNotificationsAsRead = async ( ); } - return updateQuery + const result = await updateQuery .setParameter('ids', ids) .returning('*') .updateEntity(true) .execute(); + return result.raw; }; -export const countUnreadNotifications = async (user: UserAddress) => { - const [, total] = await baseNotificationQuery(user).getManyAndCount(); - const [, projectsRelated] = await baseNotificationQuery(user) +export const countUnreadNotifications = async ( + user: UserAddress, +): Promise => { + const total = await baseNotificationQuery(user).getCount(); + const projectsRelated = await baseNotificationQuery(user) .andWhere('notificationType.category = :category', { category: NOTIFICATION_CATEGORY.PROJECT_RELATED, }) - .getManyAndCount(); - const [, givEconomyRelated] = await baseNotificationQuery(user) + .getCount(); + const givEconomyRelated = await baseNotificationQuery(user) .andWhere('notificationType.category = :category', { category: NOTIFICATION_CATEGORY.GENERAL, }) - .getManyAndCount(); - const [, general] = await baseNotificationQuery(user) + .getCount(); + const general = await baseNotificationQuery(user) .andWhere('notificationType.category = :category', { category: NOTIFICATION_CATEGORY.GIV_ECONOMY, }) - .getManyAndCount(); + .getCount(); return { total, @@ -133,4 +133,4 @@ export const createNotification = async ( metadata?: any, ) => { // TODO implement this logic -} +}; diff --git a/src/repositories/notificationTypeRepository.ts b/src/repositories/notificationTypeRepository.ts index 097f75b..c146243 100644 --- a/src/repositories/notificationTypeRepository.ts +++ b/src/repositories/notificationTypeRepository.ts @@ -1,10 +1,7 @@ -import { NotificationType } from "../entities/notificationType" +import { NotificationType } from '../entities/notificationType'; - -export const getNotificationTypeByEventName = async ( - eventName: string -) => { +export const getNotificationTypeByEventName = async (eventName: string) => { return NotificationType.createQueryBuilder() .where('name = :name', { name: eventName }) .getOne(); -} \ No newline at end of file +}; diff --git a/src/routes/v1/notificationSettingsRouter.ts b/src/routes/v1/notificationSettingsRouter.ts index 72773e7..982cf10 100644 --- a/src/routes/v1/notificationSettingsRouter.ts +++ b/src/routes/v1/notificationSettingsRouter.ts @@ -1,9 +1,5 @@ import express, { Request, Response } from 'express'; -import { - authenticateThirdPartyBasicAuth, - authenticateUser, - validateAuthMicroserviceJwt, -} from '../../middlewares/authentication'; +import { validateAuthMicroserviceJwt } from '../../middlewares/authentication'; import { NotificationSettingsController } from '../../controllers/v1/notificationSettingsController'; import { sendStandardResponse } from '../../utils/responseUtils'; diff --git a/src/utils/errorMessages.ts b/src/utils/errorMessages.ts index f268c43..d9f4b59 100644 --- a/src/utils/errorMessages.ts +++ b/src/utils/errorMessages.ts @@ -52,6 +52,7 @@ export const errorMessages = { CHANGE_API_INVALID_TITLE_OR_EIN: 'ChangeAPI title or EIN not found or invalid', INVALID_SOCIAL_NETWORK: 'Invalid social network', + NOTIFICATION_NOT_FOUND: 'Notification not found', IT_SHOULD_HAVE_ONE_OR_TWO_ADDRESSES_FOR_RECIPIENT: 'It should have one or two wallet recipient addresses', NOT_IMPLEMENTED: 'Not implemented', @@ -88,8 +89,7 @@ export const errorMessages = { JUST_ACTIVE_PROJECTS_ACCEPT_DONATION: 'Just active projects accept donation', CATEGORIES_LENGTH_SHOULD_NOT_BE_MORE_THAN_FIVE: 'Please select no more than 5 categories', - INVALID_NOTIFICATION_TYPE: - 'Notification type invalid', + INVALID_NOTIFICATION_TYPE: 'Notification type invalid', CATEGORIES_MUST_BE_FROM_THE_FRONTEND_SUBSELECTION: 'This category is not valid', INVALID_TX_HASH: 'Invalid txHash', diff --git a/src/utils/validators/segmentValidators.ts b/src/utils/validators/segmentValidators.ts index 20caf42..76e1451 100644 --- a/src/utils/validators/segmentValidators.ts +++ b/src/utils/validators/segmentValidators.ts @@ -14,7 +14,6 @@ export const validateWithJoiSchema = (data: any, schema: ObjectSchema) => { throwHttpErrorIfJoiValidatorFails(validationResult); }; - // Using Analytics structure for all notifications // Define all joi schemas here @@ -257,7 +256,8 @@ export const SCHEMA_VALIDATORS = { getDonationPriceFailed: getDonationPriceFailed, verificationFormDrafted: verificationFormDrafted, }; -function throwHttpErrorIfJoiValidatorFails(validationResult: Joi.ValidationResult) { +function throwHttpErrorIfJoiValidatorFails( + validationResult: Joi.ValidationResult, +) { throw new Error('Function not implemented.'); } - From 1c7dcdf5f03a40235dff7ecf2d201babe7df2217 Mon Sep 17 00:00:00 2001 From: Mohammad Ranjbar Z Date: Wed, 24 Aug 2022 16:42:22 +0430 Subject: [PATCH 2/2] Fix linter errors --- migrations/1661310209828-seedNotificationTemplates.ts | 4 +++- src/repositories/notificationRepository.ts | 3 +-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/migrations/1661310209828-seedNotificationTemplates.ts b/migrations/1661310209828-seedNotificationTemplates.ts index a75ba3d..788dd76 100644 --- a/migrations/1661310209828-seedNotificationTemplates.ts +++ b/migrations/1661310209828-seedNotificationTemplates.ts @@ -8,5 +8,7 @@ export class seedNotificationTemplates1661310209828 // https://www.figma.com/file/nVoinu0tgJ565enN5R4WDE/Giveth.io-%26-GIVeconomy?node-id=9820%3A181611 } - public async down(queryRunner: QueryRunner): Promise {} + public async down(queryRunner: QueryRunner): Promise { + // + } } diff --git a/src/repositories/notificationRepository.ts b/src/repositories/notificationRepository.ts index 633564b..75e1871 100644 --- a/src/repositories/notificationRepository.ts +++ b/src/repositories/notificationRepository.ts @@ -115,9 +115,8 @@ export const getNotifications = async ( } if (isRead) { - let hasBeenRead = isRead === 'true' ? true : false; query = query.andWhere('notification."isRead" = :isRead', { - isRead: hasBeenRead, + isRead: isRead === 'true', }); }