Skip to content

Commit

Permalink
#41 Updated the files and code according to the PR suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
SaiKiran0407 committed Oct 13, 2024
1 parent 15c7b88 commit 16f203f
Show file tree
Hide file tree
Showing 8 changed files with 88 additions and 103 deletions.
12 changes: 12 additions & 0 deletions server/src/__mocks__/mockDonor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export const newDonor = {
id: 1,
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
contact: '1234567890',
addressLine1: '123 Main St',
state: 'Missouri',
city: 'St. Louis',
zipcode: '63108',
emailOptIn: false
};
7 changes: 7 additions & 0 deletions server/src/__mocks__/mockNewItem.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const newItem = {
itemType: 'Book',
currentStatus: 'Received',
programId: 1,
donorId: 1,
dateDonated: new Date().toISOString()
};
7 changes: 7 additions & 0 deletions server/src/__mocks__/mockProgram.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const newProgram = {
id: 1,
name: 'Valid Program',
description: 'Valid',
startDate: '2024-10-04',
aimAndCause: 'recycle'
};
7 changes: 7 additions & 0 deletions server/src/__mocks__/mockUpdateData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const updateData = {
itemType: 'Updated Book',
currentStatus: 'Received',
programId: 1,
donorId: 1,
dateDonated: new Date().toISOString()
};
82 changes: 15 additions & 67 deletions server/src/__tests__/donatedItem.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import request from 'supertest';
import express from 'express';
import donatedItemRoutes from '../routes/donatedItemRoutes';
import mockPrismaClient from '../__mocks__/mockPrismaClient';
import { newProgram } from '../__mocks__/mockProgram';
import { newDonor } from '../__mocks__/mockDonor';
import { newItem } from '../__mocks__/mockNewItem';
import { updateData } from '../__mocks__/mockUpdateData';

const app = express();
app.use(express.json());
Expand All @@ -10,52 +14,27 @@ app.use('/donatedItem', donatedItemRoutes);
describe('DonatedItem API Tests', () => {
beforeEach(() => {
jest.clearAllMocks();
// Setup mock responses
mockPrismaClient.program.findUnique.mockResolvedValue(newProgram);
mockPrismaClient.donor.findUnique.mockResolvedValue(newDonor);
mockPrismaClient.donatedItem.create.mockResolvedValue({ id: 1, ...newItem });
mockPrismaClient.donatedItem.update.mockResolvedValue({ id: 1, ...updateData });
});

// Test POST /donatedItem
it('validates Program name and Donor email before creating a donated item', async () => {
mockPrismaClient.program.findUnique.mockResolvedValue({ id: 1, name: 'Valid Program', description: 'Valid', startDate:'2024-10-04', aimAndCause:'recycle' });
const newDonor = {
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
contact: '1234567890',
addressLine1: '123 Main St',
state: 'Missouri',
city: 'St. Louis',
zipcode: '63108',
emailOptIn: false,
};

mockPrismaClient.donor.findUnique.mockResolvedValue({
id: 1,
...newDonor,
});
const newItem = {
itemType: 'Book',
currentStatus: 'Received',
programId: 1,
donorId: 1,
dateDonated: new Date().toISOString()
};

mockPrismaClient.donatedItem.create.mockResolvedValue({
id: 1,
...newItem
});

const response = await request(app).post('/donatedItem').send(newItem);
expect(response.status).toBe(201);
expect(mockPrismaClient.donatedItem.create).toHaveBeenCalled();

});

it('handles errors when the provided Program or Donor does not exist', async () => {
mockPrismaClient.program.findUnique.mockResolvedValue(null);
mockPrismaClient.donor.findUnique.mockResolvedValue(null);

const response = await request(app).post('/donatedItem').send({
itemType: 'Book',
currentStatus: 'Received',
...newItem,
programId: 99,
donorId: 29,
dateDonated: new Date().toISOString()
Expand All @@ -66,36 +45,6 @@ describe('DonatedItem API Tests', () => {

// Test PUT /donatedItem/details/{id}
it('updates donated item details correctly', async () => {
mockPrismaClient.program.findUnique.mockResolvedValue({ id: 1, name: 'Valid Program', description: 'Valid', startDate:'2024-10-04', aimAndCause:'recycle' });
const newDonor = {
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
contact: '1234567890',
addressLine1: '123 Main St',
state: 'Missouri',
city: 'St. Louis',
zipcode: '63108',
emailOptIn: false,
};

mockPrismaClient.donor.findUnique.mockResolvedValue({
id: 1,
...newDonor,
});
const updateData = {
itemType: 'Updated Book',
currentStatus: 'Received',
programId: 1,
donorId: 1,
dateDonated: new Date().toISOString()
};

mockPrismaClient.donatedItem.update.mockResolvedValue({
id: 1,
...updateData
});

const response = await request(app).put('/donatedItem/details/1').send(updateData);
expect(response.status).toBe(200);
expect(mockPrismaClient.donatedItem.update).toHaveBeenCalled();
Expand All @@ -105,15 +54,14 @@ describe('DonatedItem API Tests', () => {
it('returns error responses for invalid Program or Donor values', async () => {
mockPrismaClient.program.findUnique.mockResolvedValue(null);
mockPrismaClient.donor.findUnique.mockResolvedValue(null);

const donorId = 19;
const programId = 99;

const response = await request(app).put('/donatedItem/details/1').send({
itemType: 'Books',
currentStatus: 'Received',
donorId: donorId,
programId: programId,
dateDonated: new Date().toISOString()
...updateData,
donorId,
programId
});
expect(response.status).toBe(400);
expect(response.body.error).toContain(`Donor with ID: ${donorId} does not exist.`);
Expand Down
54 changes: 18 additions & 36 deletions server/src/routes/donatedItemRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Router, Request, Response } from 'express';
import prisma from '../prismaClient'; // Import Prisma client
import { donatedItemValidator } from '../validators/donatedItemValidator'; // Import the validator
import { validateDonor } from '../services/donorService';
import { validateProgram } from '../services/programService';
import { date } from 'joi';

const router = Router();
Expand All @@ -11,26 +13,15 @@ router.post('/', donatedItemValidator, async (req: Request, res: Response) => {

const { dateDonated, ...rest } = req.body;

// Validate donorId
const donorExists = await prisma.donor.findUnique({
where: { id: req.body.donorId }
});


if (!donorExists) {
return res.status(400).json({ error: "Donor ID is not valid or does not exist." });
}

// Validate programId
const programExists = await prisma.program.findUnique({
where: { id: req.body.programId }
});


if (!programExists) {
return res.status(400).json({ error: "Program ID is not valid or does not exist." });
try {
await validateDonor(req.body.donorId);
await validateProgram(req.body.programId);
} catch (error) {
if (error instanceof Error) {
return res.status(400).json({ error: error.message });
}
return res.status(400).json({ error: "An unexpected error occurred" });
}

const dateDonatedDateTime = new Date(dateDonated);
dateDonatedDateTime.setUTCHours(0, 0, 0, 0); // Set time to 00:00:00 UTC

Expand All @@ -43,7 +34,6 @@ router.post('/', donatedItemValidator, async (req: Request, res: Response) => {
},
});
const newStatus = await prisma.donatedItemStatus.create({
//where: { id: Number(req.params.id) },
data: {
statusType: 'Received',
dateModified: dateDonatedDateTime, // Use the same date as dateDonated
Expand Down Expand Up @@ -86,22 +76,14 @@ router.put(
donatedItemValidator,
async (req: Request, res: Response) => {
try {
// Validate Donor ID
const donor = await prisma.donor.findUnique({
where: { id: req.body.donorId }
});

if (!donor) {
return res.status(400).json({ error: `Donor with ID: ${req.body.donorId} does not exist.` });
}

// Validate Program ID
const program = await prisma.program.findUnique({
where: { id: req.body.programId }
});

if (!program) {
return res.status(400).json({ error: `No program found with the ID: ${req.body.programId}` });
try {
await validateDonor(req.body.donorId);
await validateProgram(req.body.programId);
} catch (error) {
if (error instanceof Error) {
return res.status(400).json({ error: error.message });
}
return res.status(400).json({ error: "An unexpected error occurred" });
}

const updatedItem = await prisma.donatedItem.update({
Expand Down
11 changes: 11 additions & 0 deletions server/src/services/donorService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import prisma from '../prismaClient'; // Adjust the import path as necessary

export async function validateDonor(donorId: number) {
const donor = await prisma.donor.findUnique({
where: { id: donorId }
});
if (!donor) {
throw new Error(`Donor with ID: ${donorId} does not exist.`);
}
return donor;
}
11 changes: 11 additions & 0 deletions server/src/services/programService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import prisma from '../prismaClient'; // Adjust the import path as necessary

export async function validateProgram(programId: number) {
const program = await prisma.program.findUnique({
where: { id: programId }
});
if (!program) {
throw new Error(`Program ID ${programId} is not valid or does not exist.`);
}
return program;
}

0 comments on commit 16f203f

Please sign in to comment.