Skip to content

Instantly share code, notes, and snippets.

@falseresync
Last active August 15, 2021 19:46
Show Gist options
  • Save falseresync/e9ad60387365429c80a37663d109c79c to your computer and use it in GitHub Desktop.
Save falseresync/e9ad60387365429c80a37663d109c79c to your computer and use it in GitHub Desktop.
const MODRINTH_API = 'https://staging-api.modrinth.com/v2';
const MODRINTH_DESTINATION = 'https://staging.modrinth.com';
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
});
async function handleRequest(request) {
const { pathname } = new URL(request.url);
let statusCode = 301;
let destination = MODRINTH_DESTINATION;
const value = await MODLINK_KV.get(pathname);
if (value === null) {
const [ _, type, id ] = pathname.split('/');
let notFound = true;
switch (type) {
case 'p':
const projectString = await getProjectString(id);
if (projectString != null) {
notFound = false;
destination += projectString;
}
break;
case 'v':
// Why vresp and uresp? Because JS is dumb and treats all "cases" as a single environment
const vresp = await fetch(`${MODRINTH_API}/version/${id}`);
if (vresp.ok) {
const version = await vresp.json();
const projectString = await getProjectString(version['project_id']);
if (projectString != null) {
notFound = false;
destination += `${projectString}/version/${id}`;
}
}
break;
case 'u':
const uresp = await fetch(`${MODRINTH_API}/user/${id}`);
if (uresp.ok) {
notFound = false;
destination += `/user/${id}`;
}
break;
}
if (notFound) {
statusCode = 302;
destination += '/not-found';
} else {
MODLINK_KV.put(pathname, destination);
}
} else {
destination = value;
}
return Response.redirect(destination, statusCode);
}
async function getProjectString(id) {
const resp = await fetch(`${MODRINTH_API}/project/${id}`);
if (resp.ok) {
const project = await resp.json();
return `/${project['project_type']}/${project['slug']}`;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment