Files
pichunt/server/api/admin/hunt/[huntId]/image.post.ts
T

89 lines
1.8 KiB
TypeScript

import { useValidatedParams, z, zh } from 'h3-zod';
import { randomUUID } from 'node:crypto';
import prisma from '~~/lib/prisma';
import { minioClient, s3Bucket, s3Host } from '~~/lib/s3';
export default defineEventHandler(async (event) => {
const user = await requireUserSession(event);
if (user.user.role !== 'ADMIN') {
throw createError({
status: 403,
statusText: 'Not allowed!'
});
}
const userId = user.user.id;
const { huntId } = await useValidatedParams(
event,
z.object({
huntId: zh.numAsString
})
);
const hunt = await prisma.hunt.findUnique({
where: {
id: huntId,
OR: [
{
creatorId: userId
},
{
members: {
some: {
memberId: userId
}
}
}
]
},
select: {
id: true
}
});
if (!hunt) {
throw createError({ status: 404, statusText: 'Not found!' });
}
const body = await readFormData(event);
const formDataObj = Object.fromEntries(body.entries());
const { image } = z
.object({
image: z
.file()
.mime(['image/png', 'image/jpeg', 'image/jpg'])
.max(10_000_000)
})
.parse(formDataObj);
const uuid = randomUUID();
await minioClient.putObject(
s3Bucket,
uuid,
Buffer.from(await image.arrayBuffer()),
undefined,
{
'Cache-Control': 'public, max-age=31536000, immutable',
'Content-Type': image.type
}
);
await prisma.hunt.update({
where: {
id: huntId
},
data: {
picture: {
create: {
creatorId: userId,
url: `https://${s3Bucket}.${s3Host}/${uuid}`,
uuid,
huntId
}
}
}
});
return { success: true };
});