Skip to content

Commit

Permalink
Speed up redirect function (#82)
Browse files Browse the repository at this point in the history
  • Loading branch information
Carlgo11 authored Nov 4, 2024
1 parent df9ec2a commit e157d11
Showing 1 changed file with 10 additions and 13 deletions.
23 changes: 10 additions & 13 deletions functions/redirect.js
Original file line number Diff line number Diff line change
@@ -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}`;
Expand Down

0 comments on commit e157d11

Please sign in to comment.