Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up redirect function #82

Merged
merged 2 commits into from
Nov 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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