From 844c487ee865c512236e001907d82f89864ff2fd Mon Sep 17 00:00:00 2001 From: Ethan Davidson <31261035+EthanThatOneKid@users.noreply.github.com> Date: Sun, 22 Oct 2023 13:20:20 -0700 Subject: [PATCH] add `withCORS` helper function --- lib/api/api.ts | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/lib/api/api.ts b/lib/api/api.ts index 98c97d0..bc632a4 100644 --- a/lib/api/api.ts +++ b/lib/api/api.ts @@ -65,11 +65,11 @@ export function makeAPIRouter( ) .get( new URLPattern({ pathname: "/seasons" }), - makeSeasonsGetHandler(leaderboardClient), + withCORS(makeSeasonsGetHandler(leaderboardClient)), ) .get( new URLPattern({ pathname: "/seasons/:season_id" }), - makeSeasonGetHandler(leaderboardClient), + withCORS(makeSeasonGetHandler(leaderboardClient)), ); } @@ -115,3 +115,21 @@ export function makeOnListen( function makeInviteURL(applicationID: string) { return `https://discord.com/api/oauth2/authorize?client_id=${applicationID}&scope=applications.commands`; } + +/** + * withCORS wraps a handler with common CORS headers. + */ +function withCORS( + handle: router.RouterHandler["handle"], +): router.RouterHandler["handle"] { + return async function (request: router.RouterRequest) { + const response = await handle(request); + response.headers.set("Access-Control-Allow-Origin", "*"); + response.headers.set("Access-Control-Allow-Methods", "GET, POST"); + response.headers.set( + "Access-Control-Allow-Headers", + "Content-Type, Authorization", + ); + return response; + }; +}