From e157d118bd3587a218ea468223af073c9fbcd52a Mon Sep 17 00:00:00 2001 From: Carl Date: Mon, 4 Nov 2024 02:53:01 +0100 Subject: [PATCH] Speed up redirect function (#82) --- functions/redirect.js | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/functions/redirect.js b/functions/redirect.js index a6e0fc4..d8f0b6b 100644 --- a/functions/redirect.js +++ b/functions/redirect.js @@ -1,26 +1,23 @@ export async function onRequestGet({ request }) { const url = new URL(request.url); const base = `${url.protocol}//${url.hostname}/`; - const redirectStatus = 302; + const redirectStatus = 301; + const api = 'https://api.2fa.directory/frontend/v1/'; try { - const country = request.cf?.country?.toLowerCase() || "int"; - let uri = `${base}${country}/`; - - const res = await fetch(uri, { + const country = request.cf?.country?.toLowerCase(); + const res = await fetch(`${api}${country}/categories.json`, { + method: 'HEAD', + cache: 'force-cache', cf: { cacheTtlByStatus: { - "200": 60 * 60 * 24 * 7, // Cache request 1 week - "404": 60 * 60 * 24, // Cache request 1 day + "200": 60 * 60 * 24 * 14, // Cache request 2 weeks + "404": 60 * 60 * 24 * 7, // Cache request 1 week }, - }, + } }); - // Redirect to /int/ if that page works - if (res.status !== 200) { - const int = await fetch(`${base}int/`); - uri = int.status === 200 ? `${base}/int/` : `${base}/503/`; - } + let uri = res.status !== 200 ? `${base}${country}/` : `${base}/int/` const params = url.searchParams.toString(); if (params) uri += `?${params}`;