import { Router } from "@fastly/expressly";
const router = new Router();
const LOOKUP_LOOP_LIMIT = 16;
router.get("(.*)", async (req, res) => {
let lookupresult = lookupRedirects(req.hostname, req.path);
if (lookupresult!= null) {
let json_result = JSON.parse(lookupresult);
if ((json_result.keep_query == true)&&(req.query.toString() != "")){
json_result.path = json_result.path + "?" + req.query;
}
res.redirect(json_result.path, json_result.status);
}else{
res.send(await fetch(
req, { backend: "origin_0" }
));
}
});
router.listen();
function lookupRedirects(host, path) {
const redirects = new ConfigStore('redirects');
let key = '';
if (host && path) {
key = host + path;
const params = redirects.get(key);
if (params) {
return params;
}
}
if (path) {
key = path;
const params = redirects.get(key);
if (params) {
return params;
}
}
if (host && path) {
key = host + path.trimEnd('/');
let wildcardLookupAttempt = 0;
for (let i = 0; i < 2; i++) {
while (key.includes('/') && wildcardLookupAttempt < LOOKUP_LOOP_LIMIT) {
key += '/*';
const params = redirects.get(key);
if (params) {
return params;
}
key = key.slice(0, -2);
const n = key.lastIndexOf('/');
if (n !== -1) {
key = key.slice(0, n);
}
wildcardLookupAttempt++;
}
key ="";
key = path.trimEnd('/');
}
}
console.log('No redirection entry found');
return null;
}