Refactor transaction API to improve ID handling and error responses

This commit is contained in:
GitHub Copilot
2025-04-24 07:38:00 -04:00
parent ec8cf05a54
commit 7c9bc51a9c

View File

@@ -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<Transaction>;
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" }), {