feat : update i guess
This commit is contained in:
@@ -40,7 +40,8 @@ describe("commission message deletion", () => {
|
||||
vi.clearAllMocks();
|
||||
authorizeTicket.mockResolvedValue({ ticket: { userId: ownerId, status: "open" }, user: { id: ownerId } });
|
||||
deleteWhere.mockImplementation(() => ({ returning: deleteReturning }));
|
||||
deleteReturning.mockResolvedValue([{ imageObjectKey: "commission/messages/image-1" }]);
|
||||
deleteReturning.mockResolvedValue([{ imageObjectKey: "commission/messages/image-1",
|
||||
imageObjectKeys: ["commission/messages/image-2", "commission/messages/image-3"] }]);
|
||||
updateWhere.mockResolvedValue(undefined);
|
||||
deleteObject.mockResolvedValue(undefined);
|
||||
notifyCommission.mockResolvedValue(undefined);
|
||||
@@ -63,6 +64,8 @@ describe("commission message deletion", () => {
|
||||
expect(query.params).toContain(messageId);
|
||||
expect(query.params).toContain(ownerId);
|
||||
expect(deleteObject).toHaveBeenCalledWith("commission/messages/image-1");
|
||||
expect(deleteObject).toHaveBeenCalledWith("commission/messages/image-2");
|
||||
expect(deleteObject).toHaveBeenCalledWith("commission/messages/image-3");
|
||||
expect(notifyCommission).toHaveBeenCalledWith(ticketId, ownerId);
|
||||
});
|
||||
|
||||
|
||||
@@ -17,16 +17,20 @@ export async function DELETE(request: Request,
|
||||
const { ticket, user } = await authorizeTicket(id);
|
||||
if (ticket.status !== "open") throw new HttpError(409, "ticket-closed");
|
||||
await limitRequest("commission-message-delete", user.id, 30);
|
||||
const imageObjectKey = await getDb().transaction(async (tx) => {
|
||||
const imageObjectKeys = await getDb().transaction(async (tx) => {
|
||||
const [message] = await tx.delete(commissionMessages)
|
||||
.where(and(eq(commissionMessages.id, messageId), eq(commissionMessages.ticketId, id),
|
||||
eq(commissionMessages.authorId, user.id)))
|
||||
.returning({ imageObjectKey: commissionMessages.imageObjectKey });
|
||||
.returning({ imageObjectKey: commissionMessages.imageObjectKey,
|
||||
imageObjectKeys: commissionMessages.imageObjectKeys });
|
||||
if (!message) throw new HttpError(404, "message-not-found");
|
||||
await tx.update(commissionTickets).set({ updatedAt: new Date() }).where(eq(commissionTickets.id, id));
|
||||
return message.imageObjectKey;
|
||||
return [message.imageObjectKey, ...message.imageObjectKeys].filter((key): key is string => Boolean(key));
|
||||
});
|
||||
if (imageObjectKey) await (await getMediaStorage()).delete(imageObjectKey).catch(() => undefined);
|
||||
if (imageObjectKeys.length) {
|
||||
const storage = await getMediaStorage();
|
||||
await Promise.all(imageObjectKeys.map((key) => storage.delete(key).catch(() => undefined)));
|
||||
}
|
||||
await notifyCommission(id, ticket.userId);
|
||||
return new Response(null, { status: 204 });
|
||||
} catch (cause) { return errorResponse(cause); }
|
||||
|
||||
@@ -8,12 +8,17 @@ const selectWhere = vi.fn((condition: SQL) => { void condition; return { limit:
|
||||
const insertReturning = vi.fn();
|
||||
const insertValues = vi.fn(() => ({ returning: insertReturning }));
|
||||
const updateWhere = vi.fn();
|
||||
const writeObject = vi.fn();
|
||||
const deleteObject = vi.fn();
|
||||
const inspectImage = vi.fn();
|
||||
const tx = { insert: vi.fn(() => ({ values: insertValues })), update: vi.fn(() => ({ set: () => ({ where: updateWhere }) })) };
|
||||
const notifyCommission = vi.fn();
|
||||
|
||||
vi.mock("@/lib/commission/tickets", () => ({ authorizeTicket }));
|
||||
vi.mock("@/lib/commission/server", () => ({ notifyCommission }));
|
||||
vi.mock("@/lib/commission/push", () => ({ sendCommissionMessagePush: vi.fn() }));
|
||||
vi.mock("@/lib/media/storage", () => ({ getMediaStorage: async () => ({ write: writeObject, delete: deleteObject }) }));
|
||||
vi.mock("@/lib/media/inspect", () => ({ inspectImage }));
|
||||
vi.mock("@/lib/security/rate-limit", () => ({ limitRequest: async () => undefined }));
|
||||
vi.mock("next/server", () => ({ after: vi.fn() }));
|
||||
vi.mock("@/db", () => ({ getDb: () => ({
|
||||
@@ -47,6 +52,9 @@ describe("commission message replies", () => {
|
||||
user: { id: "user-1", name: "User" } });
|
||||
selectLimit.mockResolvedValue([{ id: parentId }]);
|
||||
insertReturning.mockResolvedValue([{ id: messageId }]);
|
||||
writeObject.mockResolvedValue(undefined);
|
||||
deleteObject.mockResolvedValue(undefined);
|
||||
inspectImage.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("accepts a reply only after looking up its parent in the same ticket", async () => {
|
||||
@@ -65,4 +73,50 @@ describe("commission message replies", () => {
|
||||
expect(response.status).toBe(404);
|
||||
expect(insertValues).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stores seven images in one message", async () => {
|
||||
const body = new FormData();
|
||||
for (let index = 0; index < 7; index++)
|
||||
body.append("image", new File(["image"], `${index}.png`, { type: "image/png" }));
|
||||
const response = await POST(new Request(`https://guide.sudloh.com/api/commission/tickets/${ticketId}/messages`, {
|
||||
method: "POST", headers: { Origin: "https://guide.sudloh.com" }, body,
|
||||
}), context());
|
||||
expect(response.status).toBe(201);
|
||||
expect(writeObject).toHaveBeenCalledTimes(7);
|
||||
expect(insertValues).toHaveBeenCalledWith(expect.objectContaining({
|
||||
imageObjectKeys: writeObject.mock.calls.map(([key]) => key),
|
||||
}));
|
||||
});
|
||||
|
||||
it("rejects more than ten images before uploading", async () => {
|
||||
const body = new FormData();
|
||||
for (let index = 0; index < 11; index++)
|
||||
body.append("image", new File(["image"], `${index}.png`, { type: "image/png" }));
|
||||
const response = await POST(new Request(`https://guide.sudloh.com/api/commission/tickets/${ticketId}/messages`, {
|
||||
method: "POST", headers: { Origin: "https://guide.sudloh.com" }, body,
|
||||
}), context());
|
||||
expect(response.status).toBe(400);
|
||||
expect(writeObject).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cleans up uploaded images when saving the message fails", async () => {
|
||||
insertReturning.mockRejectedValueOnce(new Error("database unavailable"));
|
||||
const body = new FormData();
|
||||
body.append("image", new File(["image"], "first.png", { type: "image/png" }));
|
||||
const response = await POST(new Request(`https://guide.sudloh.com/api/commission/tickets/${ticketId}/messages`, {
|
||||
method: "POST", headers: { Origin: "https://guide.sudloh.com" }, body,
|
||||
}), context());
|
||||
expect(response.status).toBe(503);
|
||||
expect(deleteObject).toHaveBeenCalledWith(writeObject.mock.calls[0][0]);
|
||||
});
|
||||
|
||||
it("rejects an image larger than ten MiB", async () => {
|
||||
const body = new FormData();
|
||||
body.append("image", new File([new Uint8Array(10 * 1024 * 1024 + 1)], "large.png", { type: "image/png" }));
|
||||
const response = await POST(new Request(`https://guide.sudloh.com/api/commission/tickets/${ticketId}/messages`, {
|
||||
method: "POST", headers: { Origin: "https://guide.sudloh.com" }, body,
|
||||
}), context());
|
||||
expect(response.status).toBe(415);
|
||||
expect(writeObject).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -22,13 +22,13 @@ export async function POST(request: Request, context: RouteContext<"/api/commiss
|
||||
if (!request.headers.get("content-type")?.startsWith("multipart/form-data;"))
|
||||
throw new HttpError(415, "expected-multipart");
|
||||
return await withUploadSlot(async () => {
|
||||
const form = await boundedBody(request, 6 * 1024 * 1024 + 64 * 1024).formData();
|
||||
const form = await boundedBody(request, 10 * 10 * 1024 * 1024 + 64 * 1024).formData();
|
||||
const value = form.get("text");
|
||||
const body = typeof value === "string" ? value.trim() : "";
|
||||
const image = form.get("image");
|
||||
const images = form.getAll("image");
|
||||
const replyValue = form.get("replyToId");
|
||||
const replyToId = replyValue === null || replyValue === "" ? null : replyValue;
|
||||
if (body.length > 4000 || (image && !(image instanceof File)))
|
||||
if (body.length > 4000 || images.length > 10 || images.some((image) => !(image instanceof File)))
|
||||
throw new HttpError(400, "invalid-message");
|
||||
if (replyToId !== null) {
|
||||
if (typeof replyToId !== "string" || !z.uuid().safeParse(replyToId).success)
|
||||
@@ -37,28 +37,34 @@ export async function POST(request: Request, context: RouteContext<"/api/commiss
|
||||
.where(and(eq(commissionMessages.id, replyToId), eq(commissionMessages.ticketId, id))).limit(1);
|
||||
if (!parent) throw new HttpError(404, "reply-not-found");
|
||||
}
|
||||
if (!body && !image) throw new HttpError(400, "empty-message");
|
||||
let imageObjectKey: string | null = null;
|
||||
if (image instanceof File) {
|
||||
if (image.size === 0 || image.size > 6 * 1024 * 1024 ||
|
||||
!["image/png", "image/jpeg", "image/webp"].includes(image.type))
|
||||
throw new HttpError(415, "invalid-message-image");
|
||||
const bytes = new Uint8Array(await image.arrayBuffer());
|
||||
await inspectImage(bytes, image.type as "image/png" | "image/jpeg" | "image/webp");
|
||||
imageObjectKey = `commission/messages/${crypto.randomUUID()}`;
|
||||
await (await getMediaStorage()).write(imageObjectKey, bytes, { type: image.type, acl: "public-read" });
|
||||
}
|
||||
if (!body && !images.length) throw new HttpError(400, "empty-message");
|
||||
const imageFiles = images as File[];
|
||||
if (imageFiles.some((image) => image.size === 0 || image.size > 10 * 1024 * 1024 ||
|
||||
!["image/png", "image/jpeg", "image/webp"].includes(image.type)))
|
||||
throw new HttpError(415, "invalid-message-image");
|
||||
const imageObjectKeys: string[] = [];
|
||||
let messageId: string;
|
||||
try {
|
||||
const storage = imageFiles.length ? await getMediaStorage() : null;
|
||||
for (const image of imageFiles) {
|
||||
const bytes = new Uint8Array(await image.arrayBuffer());
|
||||
await inspectImage(bytes, image.type as "image/png" | "image/jpeg" | "image/webp");
|
||||
const key = `commission/messages/${crypto.randomUUID()}`;
|
||||
imageObjectKeys.push(key);
|
||||
await storage!.write(key, bytes, { type: image.type, acl: "public-read" });
|
||||
}
|
||||
messageId = await getDb().transaction(async (tx) => {
|
||||
const [message] = await tx.insert(commissionMessages).values({ ticketId: id, authorId: user.id, replyToId,
|
||||
text: body || null, imageObjectKey, imageMimeType: image instanceof File ? image.type : null })
|
||||
text: body || null, imageObjectKeys })
|
||||
.returning({ id: commissionMessages.id });
|
||||
await tx.update(commissionTickets).set({ updatedAt: new Date() }).where(eq(commissionTickets.id, id));
|
||||
return message.id;
|
||||
});
|
||||
} catch (cause) {
|
||||
if (imageObjectKey) await (await getMediaStorage()).delete(imageObjectKey).catch(() => undefined);
|
||||
if (imageObjectKeys.length) {
|
||||
const storage = await getMediaStorage();
|
||||
await Promise.all(imageObjectKeys.map((key) => storage.delete(key).catch(() => undefined)));
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
const message: CommissionMessageEvent = { messageId, ticketId: id,
|
||||
|
||||
Reference in New Issue
Block a user