From 9aa100f1c10a15aab4d3ede198d1e960a3c9106a Mon Sep 17 00:00:00 2001 From: Regalijan Date: Sat, 26 Oct 2024 02:39:33 -0400 Subject: [PATCH] Add PATCH request handler for short links --- functions/api/short-links/[id].ts | 34 +++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/functions/api/short-links/[id].ts b/functions/api/short-links/[id].ts index 3b566d5..fbc6b4b 100644 --- a/functions/api/short-links/[id].ts +++ b/functions/api/short-links/[id].ts @@ -15,3 +15,37 @@ export async function onRequestDelete(context: RequestContext) { status: 204, }); } + +export async function onRequestPatch(context: RequestContext) { + const { body } = context.data; + + if (!body) return jsonError("Request body missing", 400); + + let data: { path: any }; + + try { + data = JSON.parse(body); + } catch { + return jsonError("Invalid JSON", 400); + } + + if (Object.keys(data).find((k) => k !== "path")) + return jsonError("Only the `path` property can be modified.", 400); + + const { path } = data; + + if (typeof path !== "string") + return jsonError("The `path` property must be a string", 400); + + if (path.length > 256) return jsonError("Path is too long", 400); + + await context.env.D1.prepare( + "UPDATE short_links SET path = ? WHERE path = ? AND user = ?;", + ) + .bind(path, context.params.id, context.data.current_user.id) + .run(); + + return new Response(null, { + status: 204, + }); +}