Created
November 2, 2020 13:10
-
-
Save phamann/6fc7a3bf789bab12abdf0e45e9202ea0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Request, Response, Fastly } from "@fastly/as-compute"; | |
const HTTPBIN_BACKEND = "httpbin"; | |
function badRequest(): Response { | |
return new Response(String.UTF8.encode("Bad request"), { | |
status: 400 | |
}); | |
} | |
function uuidHandler(req: Request): Response { | |
let parts = req.url().split("/"); | |
if (parts.length != 5) { | |
return badRequest(); | |
} | |
let i = parts[4]; | |
let limit = I32.parseInt(i); | |
if(isNaN(limit)) { | |
return badRequest(); | |
} | |
let pool = new Fastly.FetchPool(); | |
let headers = req.headers(); | |
headers.set("Host", "httpbin.org"); | |
let cacheOverride = new Fastly.CacheOverride(); | |
cacheOverride.setTTL(0); | |
for(let i = 0; i < limit; i++) { | |
let r = new Request("https://httpbin.org/uuid", { | |
method: "GET", | |
headers: headers, | |
body: null | |
}); | |
pool.push(Fastly.fetch(r, { | |
backend: HTTPBIN_BACKEND, | |
cacheOverride, | |
})); | |
} | |
let json = pool.all().reduce((json, r, i, arr) => { | |
json += r.response.text(); | |
if(i != arr.length-1) json += ","; | |
return json; | |
}, "[") + "]"; | |
json = json.replaceAll(" ", ""); | |
json = json.replaceAll("\n", ""); | |
return new Response(String.UTF8.encode(json), { status: 200 }); | |
} | |
function main(req: Request): Response { | |
let method = req.method(); | |
let urlParts = req.url().split("//").pop().split("/"); | |
let host = urlParts.shift(); | |
let path = "/" + urlParts.join("/"); | |
if (method == "GET" && path.startsWith("/uuid")) { | |
return uuidHandler(req); | |
} | |
return new Response(String.UTF8.encode("The page you requested could not be found"), { | |
status: 200, | |
}); | |
} | |
let req = Fastly.getClientRequest(); | |
let resp = main(req); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment