From d13da35d1447041546975e68708a0b0838ed37cc Mon Sep 17 00:00:00 2001
From: lambeb <141648830+lambeb@users.noreply.github.com>
Date: Mon, 28 Oct 2024 18:16:25 +0000
Subject: [PATCH] Fixed issues with calling cloud function, now works correctly

---
 .../reissueNewDonorCaseConfirmation.tsx       |  2 +-
 .../handlers/cloudFunctionHandler.test.ts     | 22 +++++++--------
 src/server/handlers/cloudFunctionHandler.ts   | 22 +++++++++++----
 .../helpers/cloudFunctionCallerHelper.test.ts |  6 ++---
 .../helpers/cloudFunctionCallerHelper.ts      | 27 +------------------
 src/server/server.ts                          |  3 ++-
 6 files changed, 35 insertions(+), 47 deletions(-)

diff --git a/src/components/reissueNewDonorCasePage/reissueNewDonorCaseConfirmation.tsx b/src/components/reissueNewDonorCasePage/reissueNewDonorCaseConfirmation.tsx
index 2c7c82e4..8dc09ae0 100644
--- a/src/components/reissueNewDonorCasePage/reissueNewDonorCaseConfirmation.tsx
+++ b/src/components/reissueNewDonorCasePage/reissueNewDonorCaseConfirmation.tsx
@@ -21,7 +21,7 @@ function ReissueNewDonorCaseConfirmation(): ReactElement {
 
     async function callReissueNewDonorCaseCloudFunction() {
         isLoading(true);
-        const payload = { questionnaire_name: questionnaire.name, role: user };
+        const payload = { questionnaire_name: questionnaire.name, user: user };
         let res;
         try {
             res = await axios.post("/api/cloudFunction/reissueNewDonorCase", payload, axiosConfig());
diff --git a/src/server/handlers/cloudFunctionHandler.test.ts b/src/server/handlers/cloudFunctionHandler.test.ts
index 15467f80..e6335cd8 100644
--- a/src/server/handlers/cloudFunctionHandler.test.ts
+++ b/src/server/handlers/cloudFunctionHandler.test.ts
@@ -4,7 +4,7 @@ import { newServer } from "../server";
 import supertest from "supertest";
 import { getConfigFromEnv } from "../config";
 import createLogger from "../pino";
-import { callCloudFunctionToCreateDonorCases } from "../helpers/cloudFunctionCallerHelper";
+import { callCloudFunction } from "../helpers/cloudFunctionCallerHelper";
 import { cloudFunctionAxiosError } from "../../features/step_definitions/helpers/apiMockObjects";
 
 jest.mock("../helpers/cloudFunctionCallerHelper");
@@ -14,33 +14,33 @@ const successResponse = {
 };
 
 const config = getConfigFromEnv();
-const callCloudFunctionToCreateDonorCasesMock = callCloudFunctionToCreateDonorCases as jest.Mock<Promise<{ message: string, status: number }>>;
+const callCloudFunctionToCreateDonorCasesMock = callCloudFunction as jest.Mock<Promise<{ message: string, status: number }>>;
 
 describe("Call Cloud Function to create donor cases and return responses", () => {
     let request: supertest.SuperTest<supertest.Test>;
-  
+
     beforeEach(() => {
         request = supertest(newServer(config, createLogger()));
     });
-  
+
     afterEach(() => {
-        jest.clearAllMocks(); 
+        jest.clearAllMocks();
     });
-  
+
     it("should return a 200 status and a json object with message and status if successfully created donor cases", async () => {
         callCloudFunctionToCreateDonorCasesMock.mockResolvedValue(successResponse);
-  
+
         const response = await request.post("/api/cloudFunction/createDonorCases");
-  
+
         expect(response.status).toEqual(200);
         expect(response.body).toEqual(successResponse);
     });
-  
+
     it("should return a 500 status and a json object with message and status if cloud function failed creating donor cases", async () => {
         callCloudFunctionToCreateDonorCasesMock.mockRejectedValue(cloudFunctionAxiosError);
-  
+
         const response = await request.post("/api/cloudFunction/createDonorCases");
-  
+
         expect(response.status).toEqual(500);
         expect(response.body.message).toEqual((cloudFunctionAxiosError as any).response.data);
     });
diff --git a/src/server/handlers/cloudFunctionHandler.ts b/src/server/handlers/cloudFunctionHandler.ts
index 1f6ca9b1..8ac31563 100644
--- a/src/server/handlers/cloudFunctionHandler.ts
+++ b/src/server/handlers/cloudFunctionHandler.ts
@@ -1,5 +1,5 @@
 import express, { Request, Response, Router } from "express";
-import { callCloudFunctionToCreateDonorCases } from "../helpers/cloudFunctionCallerHelper";
+import { callCloudFunction } from "../helpers/cloudFunctionCallerHelper";
 
 export default function newCloudFunctionHandler(
     CreateDonorCasesCloudFunctionUrl: string
@@ -13,19 +13,31 @@ export default function newCloudFunctionHandler(
     return router;
 }
 
+export function reissueNewDonorCaseCloudFunctionHandler(
+    CloudFunctionUrl: string
+): Router {
+    const router = express.Router();
+    const cloudFunctionHandler = new CloudFunctionHandler(
+        CloudFunctionUrl
+    );
+    router.post("/api/cloudFunction/reissueNewDonorCase", cloudFunctionHandler.CallCloudFunction);
+
+    return router;
+}
+
 export class CloudFunctionHandler {
-    CreateDonorCasesCloudFunctionUrl: string;
+    CloudFunctionUrl: string;
 
     constructor(CreateDonorCasesCloudFunctionUrl: string) {
-        this.CreateDonorCasesCloudFunctionUrl = CreateDonorCasesCloudFunctionUrl;
+        this.CloudFunctionUrl = CreateDonorCasesCloudFunctionUrl;
         this.CallCloudFunction = this.CallCloudFunction.bind(this);
     }
 
     async CallCloudFunction(req: Request, res: Response): Promise<Response> {
         const reqData = req.body;
-        req.log.info(`${this.CreateDonorCasesCloudFunctionUrl} URL to invoke for Creating Donor Cases.`);
+        req.log.info(`${this.CloudFunctionUrl} URL to invoke for Creating Donor Cases.`);
         try {
-            const cloudfunctionResponse = await callCloudFunctionToCreateDonorCases(this.CreateDonorCasesCloudFunctionUrl, reqData);
+            const cloudfunctionResponse = await callCloudFunction(this.CloudFunctionUrl, reqData);
             return res.status(cloudfunctionResponse.status).json(cloudfunctionResponse);
 
         } catch (error) {
diff --git a/src/server/helpers/cloudFunctionCallerHelper.test.ts b/src/server/helpers/cloudFunctionCallerHelper.test.ts
index 8c4101e6..15f73781 100644
--- a/src/server/helpers/cloudFunctionCallerHelper.test.ts
+++ b/src/server/helpers/cloudFunctionCallerHelper.test.ts
@@ -1,5 +1,5 @@
 import { getConfigFromEnv } from "../config";
-import { callCloudFunctionToCreateDonorCases } from "./cloudFunctionCallerHelper";
+import { callCloudFunction } from "./cloudFunctionCallerHelper";
 import axios from "axios";
 import { ipsQuestionnaire } from "../../features/step_definitions/helpers/apiMockObjects";
 import { GoogleAuth } from "google-auth-library";
@@ -47,7 +47,7 @@ describe("Call Cloud Function to create donor cases and return responses", () =>
             status: mockSuccessResponse.status,
         });
 
-        const result = await callCloudFunctionToCreateDonorCases(
+        const result = await callCloudFunction(
             dummyUrl,
             payload
         );
@@ -84,7 +84,7 @@ describe("Call Cloud Function to create donor cases and return responses", () =>
             status: mockErrorResponse.status,
         });
 
-        const result = await callCloudFunctionToCreateDonorCases(
+        const result = await callCloudFunction(
             dummyUrl,
             payload
         );
diff --git a/src/server/helpers/cloudFunctionCallerHelper.ts b/src/server/helpers/cloudFunctionCallerHelper.ts
index 1492f15a..42d3f774 100644
--- a/src/server/helpers/cloudFunctionCallerHelper.ts
+++ b/src/server/helpers/cloudFunctionCallerHelper.ts
@@ -9,32 +9,7 @@ export async function getIdTokenFromMetadataServer(targetAudience: string) {
     return await client.idTokenProvider.fetchIdToken(targetAudience);
 }
 
-export async function callCloudFunctionToCreateDonorCases(url: string, payload: any): Promise<{ message: string, status: number }> {
-
-    const token = await getIdTokenFromMetadataServer(url);
-
-    try {
-        const res = await axios.post(url, payload, {
-            headers: {
-                "Content-Type": "application/json",
-                Authorization: `Bearer ${token}`,
-            },
-        });
-
-        return {
-            message: res.data,
-            status: res.status
-        };
-    } catch (error) {
-        console.error("Error:", error);
-        return {
-            message: (error as any).response.data,
-            status: 500
-        };
-    }
-}
-
-export async function callCloudFunctionToReissueNewDonorDonorCase(url: string, payload: any): Promise<{ message: string, status: number }> {
+export async function callCloudFunction(url: string, payload: any): Promise<{ message: string, status: number }> {
 
     const token = await getIdTokenFromMetadataServer(url);
 
diff --git a/src/server/server.ts b/src/server/server.ts
index 33a75308..c048de2d 100644
--- a/src/server/server.ts
+++ b/src/server/server.ts
@@ -18,6 +18,7 @@ import { HttpLogger } from "pino-http";
 import AuditLogger from "./auditLogging/logger";
 import newAuditHandler from "./handlers/auditHandler";
 import newCloudFunctionHandler from "./handlers/cloudFunctionHandler";
+import { reissueNewDonorCaseCloudFunctionHandler } from "./handlers/cloudFunctionHandler";
 
 if (process.env.NODE_ENV === "production") {
     import("@google-cloud/profiler").then((profiler) => {
@@ -45,7 +46,7 @@ export function newServer(config: Config, logger: HttpLogger = createLogger()):
     const uploadHandler = newUploadHandler(storageManager, auth, auditLogger);
     const auditHandler = newAuditHandler(auditLogger);
     const cloudFunctionHandler = newCloudFunctionHandler(config.CreateDonorCasesCloudFunctionUrl);
-    const reissueNewDonorCaseHandler = newCloudFunctionHandler(config.ReissueNewDonorCaseCloudFunctionUrl);
+    const reissueNewDonorCaseHandler = reissueNewDonorCaseCloudFunctionHandler(config.ReissueNewDonorCaseCloudFunctionUrl);
 
     const server = express();