Skip to content

Commit

Permalink
add basic put route
Browse files Browse the repository at this point in the history
  • Loading branch information
kristianka committed Jun 10, 2024
1 parent d05f7d6 commit 53f4925
Showing 1 changed file with 91 additions and 2 deletions.
93 changes: 91 additions & 2 deletions backend/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Fastify, { FastifySchema } from "fastify";
import { PrismaClient } from "@prisma/client";
import { Prisma, PrismaClient } from "@prisma/client";
import dotenv from "dotenv";
import cors from "@fastify/cors";
import { Box } from "./types";
Expand All @@ -8,7 +8,7 @@ dotenv.config();
const prisma = new PrismaClient();

const fastify = Fastify({
logger: true,
logger: false,
});

fastify.register(cors, {
Expand All @@ -28,6 +28,42 @@ const boxSchema: FastifySchema = {
},
};

const updateBoxSchema: FastifySchema = {
params: {
type: "object",
properties: {
id: { type: "string" },
},
required: ["id"],
},
body: {
type: "object",
properties: {
width: { type: "number" },
height: { type: "number" },
depth: { type: "number" },
comment: { type: "string" },
},
},
};

function validateDimensions(
width: unknown,
height: unknown,
depth: unknown,
): string | null {
// Check if the values exist and are less than or equal to 0
if (
(width !== null && width !== undefined && Number(width) <= 0) ||
(height !== null && height !== undefined && Number(height) <= 0) ||
(depth !== null && depth !== undefined && Number(depth) <= 0)
) {
return "Width, height, and depth must be greater than 0.";
}
// no error
return null;
}

const PORT = Number(process.env.PORT) || 3000;

fastify.get("/", async function handler(_request, _reply) {
Expand Down Expand Up @@ -83,6 +119,59 @@ fastify.post<{ Body: Box }>(
},
);

// Step 1: Define an interface for the route parameters
interface RouteParams {
id: string; // Assuming id is passed as a string
}

fastify.put<{ Params: RouteParams; Body: Partial<Box> }>(
"/boxes/:id",
{ schema: updateBoxSchema },
async function handler(request, reply) {
try {
// Fastify schema validation ensures that width, height, and depth are not missing
// string is converted automatically to number if possible
const { width, height, depth, comment } = request.body;
const { id } = request.params;
const numericId = Number(id);

const validationError = validateDimensions(width, height, depth);
if (validationError) {
return reply.code(400).send({ error: validationError });
}

// update only necessary fields
const updatedBox = await prisma.boxes.update({
where: { id: numericId },
data: {
...(width !== undefined && { width }),
...(height !== undefined && { height }),
...(depth !== undefined && { depth }),
...(comment !== undefined && { comment }),
},
});

return reply.code(201).send(updatedBox);
} catch (error) {
console.log("An error occurred while creating a box: \n", error);
// prisma errors
if (error instanceof Prisma.PrismaClientKnownRequestError) {
console.log("Prisma error", error.code);
if (error.code === "P2025") {
// Prisma's code for record not found
return reply.code(404).send({
error: "Box not found.",
});
}
}

return reply.code(500).send({
error: "Internal Server Error. Read the server console for more information.",
});
}
},
);

const start = async () => {
try {
if (!process.env.FRONTEND_URL) {
Expand Down

0 comments on commit 53f4925

Please sign in to comment.