Skip to content

Instantly share code, notes, and snippets.

@RickSandov
Created July 25, 2024 07:33
Show Gist options
  • Save RickSandov/dd51b18a63b0f56e5276b4fb3b718c3c to your computer and use it in GitHub Desktop.
Save RickSandov/dd51b18a63b0f56e5276b4fb3b718c3c to your computer and use it in GitHub Desktop.
POST /time-events con almacenamiento de imagen en S3 y registro en MongoDB
/*
Considero que es un buen ejemplo ya que tengo una buena separación
de responsabilidades en el código, el endpoint crea un evento de tiempo,
almacena la imagen en un bucket de S3 y registro en MongoDB
*/
export const POST = async (req: NextRequest) => {
const formData = await req.formData();
const body = Object.fromEntries(formData);
const image = (body.image as File) || null;
const description = (body.description as string);
const date = (body.date as string);
const title = (body.title as string);
if (!image || !description || !date || !title) {
return NextResponse.json(
{
msg: "Completa los campos obligatorios",
},
{ status: 400 }
);
}
try {
await db.connect();
const timeEvent = await createTimeEvent({
date,
description,
title,
image,
});
await db.disconnect();
return NextResponse.json(timeEvent, { status: 201 });
} catch (error) {
console.log("POST /time-event: ", error);
await db.disconnect();
return NextResponse.json(
{
error,
},
{ status: 500 }
);
}
};
// time-events.controller.ts
export const createTimeEvent = async (
timeEvent: TPostTimeEvent
): Promise<TTimeEvent> => {
const { date, description, title, image } = timeEvent;
try {
const buffer = Buffer.from(await image.arrayBuffer());
const imageKey = `${date}.${image.name.split(".").pop()}`;
await uploadFile(buffer, imageKey);
const newTimeEvent = new TimeEvent({
date: new Date(date),
description,
title,
image: {
url: `${bucketAccessName}/${imageKey}`,
key: imageKey,
},
});
await newTimeEvent.save();
return newTimeEvent;
} catch (error) {
console.log("Error from createTimeEvent:", error);
throw error;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment