Skip to content

Commit

Permalink
Add delete email template for admin and unit tests (#132)
Browse files Browse the repository at this point in the history
Co-authored-by: Dileepa Mabulage <[email protected]>
  • Loading branch information
dsmabulage and dileepainivossl authored Jul 12, 2024
1 parent 0df9fb3 commit 519c6d3
Show file tree
Hide file tree
Showing 4 changed files with 140 additions and 6 deletions.
25 changes: 23 additions & 2 deletions src/controllers/admin/emailTemplate.controller.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import type { Request, Response } from 'express'
import type { ApiResponse } from '../../types'
import type EmailTemplate from '../../entities/emailTemplate.entity'
import type Profile from '../../entities/profile.entity'
import { ProfileTypes } from '../../enums'
import {
createEmailTemplate,
deleteEmailTemplateById,
getEmailTemplateById
} from '../../services/admin/emailTemplate.service'
import type EmailTemplate from '../../entities/emailTemplate.entity'
import type { ApiResponse } from '../../types'

export const addEmailTemplate = async (
req: Request,
Expand Down Expand Up @@ -57,3 +58,23 @@ export const getEmailTemplate = async (
return res.status(500).json({ error: err })
}
}

export const deleteEmailTemplate = async (
req: Request,
res: Response
): Promise<ApiResponse<EmailTemplate>> => {
try {
const user = req.user as Profile
const templateId = req.params.templateId

if (user.type !== ProfileTypes.ADMIN) {
return res.status(403).json({ message: 'Only Admins are allowed' })
}

const { statusCode, message } = await deleteEmailTemplateById(templateId)
return res.status(statusCode).json({ message })
} catch (err) {
console.error('Error executing query', err)
return res.status(500).json({ error: err })
}
}
4 changes: 3 additions & 1 deletion src/routes/admin/email/emailTemplate.route.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import express from 'express'
import { requireAuth } from '../../../controllers/auth.controller'
import {
addEmailTemplate,
deleteEmailTemplate,
getEmailTemplate
} from '../../../controllers/admin/emailTemplate.controller'
import { requireAuth } from '../../../controllers/auth.controller'

const emailTemplateRouter = express.Router()

emailTemplateRouter.post('/', requireAuth, addEmailTemplate)
emailTemplateRouter.get('/:templateId', requireAuth, getEmailTemplate)
emailTemplateRouter.delete('/:templateId', requireAuth, deleteEmailTemplate)

export default emailTemplateRouter
81 changes: 80 additions & 1 deletion src/services/admin/emailTemplate.service.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { dataSource } from '../../configs/dbConfig'
import {
createEmailTemplate,
deleteEmailTemplateById,
getEmailTemplateById
} from './emailTemplate.service'
import { dataSource } from '../../configs/dbConfig'

jest.mock('../../configs/dbConfig', () => ({
dataSource: {
Expand Down Expand Up @@ -122,4 +123,82 @@ describe('Email Template Service', () => {
)
})
})

describe('deleteEmailTemplateById', () => {
it('should delete an email template by ID successfully', async () => {
const templateId = 'mock-uuid'

const mockEmailTemplateRepository = {
findOne: jest.fn().mockResolvedValue({
uuid: templateId,
subject: 'Test Subject',
content: 'Test Content',
created_at: new Date(),
updated_at: new Date(),
updateTimestamps: jest.fn(),
generateUuid: jest.fn()
}),
remove: jest.fn().mockResolvedValue({
uuid: templateId,
subject: 'Test Subject',
content: 'Test Content',
created_at: new Date(),
updated_at: new Date(),
updateTimestamps: jest.fn(),
generateUuid: jest.fn()
})
}

;(dataSource.getRepository as jest.Mock).mockReturnValueOnce(
mockEmailTemplateRepository
)

const result = await deleteEmailTemplateById(templateId)

expect(result.statusCode).toBe(200)
expect(result.message).toBe('Email template deleted successfully')
})

it('should handle email template not found during deletion', async () => {
const templateId = 'nonexistent-uuid'

const mockEmailTemplateRepository = {
findOne: jest.fn().mockResolvedValue(null)
}

;(dataSource.getRepository as jest.Mock).mockReturnValueOnce(
mockEmailTemplateRepository
)

const result = await deleteEmailTemplateById(templateId)

expect(result.statusCode).toBe(404)
expect(result.message).toBe('Email template not found')
})

it('should handle error during email template deletion', async () => {
const templateId = 'mock-uuid'

const mockEmailTemplateRepository = {
findOne: jest.fn().mockResolvedValue({
uuid: templateId,
subject: 'Test Subject',
content: 'Test Content',
created_at: new Date(),
updated_at: new Date(),
updateTimestamps: jest.fn(),
generateUuid: jest.fn()
}),
remove: jest.fn().mockRejectedValue(new Error('Test repository error'))
}

;(dataSource.getRepository as jest.Mock).mockReturnValueOnce(
mockEmailTemplateRepository
)

await expect(deleteEmailTemplateById(templateId)).rejects.toThrowError(
'Error deleting email template'
)
})
})
})
36 changes: 34 additions & 2 deletions src/services/admin/emailTemplate.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ export const getEmailTemplateById = async (
message: string
}> => {
try {
const emailRepositroy = dataSource.getRepository(EmailTemplate)
const emailRepository = dataSource.getRepository(EmailTemplate)

const emailTemplate = await emailRepositroy.findOne({
const emailTemplate = await emailRepository.findOne({
where: { uuid: templateId },
select: ['uuid', 'content', 'subject']
})
Expand All @@ -61,3 +61,35 @@ export const getEmailTemplateById = async (
throw new Error('Error getting email template')
}
}

export const deleteEmailTemplateById = async (
templateId: string
): Promise<{
statusCode: number
message: string
}> => {
try {
const emailRepository = dataSource.getRepository(EmailTemplate)

const emailTemplate = await emailRepository.findOne({
where: { uuid: templateId }
})

if (!emailTemplate) {
return {
statusCode: 404,
message: 'Email template not found'
}
}

await emailRepository.remove(emailTemplate)

return {
statusCode: 200,
message: 'Email template deleted successfully'
}
} catch (err) {
console.error('Error deleting email template', err)
throw new Error('Error deleting email template')
}
}

0 comments on commit 519c6d3

Please sign in to comment.