From ebc0b5e81fca5d6277a521fc146479c412508853 Mon Sep 17 00:00:00 2001 From: regalijan Date: Thu, 19 Oct 2023 16:51:11 -0400 Subject: [PATCH] Create send notification endpoint --- functions/api/notifications/send.ts | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 functions/api/notifications/send.ts diff --git a/functions/api/notifications/send.ts b/functions/api/notifications/send.ts new file mode 100644 index 0000000..2851130 --- /dev/null +++ b/functions/api/notifications/send.ts @@ -0,0 +1,35 @@ +import { jsonError } from "../../common.js"; +import { sendPushNotification } from "../../gcloud.js"; + +export async function onRequestPost(context: RequestContext) { + const { current_user: currentUser } = context.data; + + if (!currentUser) return jsonError("Unauthorized", 401); + + if (!(currentUser.permissions & (1 << 0))) return jsonError("Forbidden", 403); + + const { body, title } = context.data.body; + + if (typeof body !== "string" || typeof title !== "string") + return jsonError("Body and title must be strings", 400); + + if ( + new Blob([ + JSON.stringify({ + message: { + notification: { + body, + title, + }, + }, + }), + ]).size > 4000 + ) + return jsonError("Payload too large", 400); + + await sendPushNotification(context.env, title, body); + + return new Response(null, { + status: 204, + }); +}