From 7c9bc51a9cf2f46f2197e04b63dd374b4331df41 Mon Sep 17 00:00:00 2001 From: GitHub Copilot Date: Thu, 24 Apr 2025 07:38:00 -0400 Subject: [PATCH] Refactor transaction API to improve ID handling and error responses --- src/pages/api/transactions/[id]/index.ts | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/pages/api/transactions/[id]/index.ts b/src/pages/api/transactions/[id]/index.ts index 8b778e3..8efd606 100644 --- a/src/pages/api/transactions/[id]/index.ts +++ b/src/pages/api/transactions/[id]/index.ts @@ -3,9 +3,18 @@ import { transactions, accounts } from "../../../../data/store"; import type { Transaction } from "../../../../types"; export const PUT: APIRoute = async ({ request, params }) => { + const { id } = params; + + if (!id) { + return new Response(JSON.stringify({ error: "Transaction ID is required" }), { + status: 400, + headers: { "Content-Type": "application/json" }, + }); + } + try { const updates = (await request.json()) as Partial; - const transactionIndex = transactions.findIndex((t) => t.id === params.id); + const transactionIndex = transactions.findIndex((t) => t.id === id); if (transactionIndex === -1) { return new Response(JSON.stringify({ error: "Transaction not found" }), { @@ -31,7 +40,7 @@ export const PUT: APIRoute = async ({ request, params }) => { const updatedTransaction: Transaction = { ...oldTransaction, ...updates, - id: params.id, // Ensure ID doesn't change + id: id, // Ensure ID doesn't change }; // Add new amount to account balance @@ -53,7 +62,16 @@ export const PUT: APIRoute = async ({ request, params }) => { }; export const DELETE: APIRoute = async ({ params }) => { - const transactionIndex = transactions.findIndex((t) => t.id === params.id); + const { id } = params; + + if (!id) { + return new Response(JSON.stringify({ error: "Transaction ID is required" }), { + status: 400, + headers: { "Content-Type": "application/json" }, + }); + } + + const transactionIndex = transactions.findIndex((t) => t.id === id); if (transactionIndex === -1) { return new Response(JSON.stringify({ error: "Transaction not found" }), {