Skip to content

Instantly share code, notes, and snippets.

@mikaelvesavuori
Last active May 6, 2023 10:23
Show Gist options
  • Save mikaelvesavuori/8cf9d52f6341c344211af7ac7afbc845 to your computer and use it in GitHub Desktop.
Save mikaelvesavuori/8cf9d52f6341c344211af7ac7afbc845 to your computer and use it in GitHub Desktop.
Repro of inability to call GitHub from Cloudflare Workers. Solution: This can be solved by adding the "User-Agent" header to calls.
/**
* @description This is the entry point for the Cloudflare Worker.
* Call it with `http://0.0.0.0:8787?endpoint=gh` or `http://0.0.0.0:8787?endpoint=swapi`
*/
export default {
async fetch(request: Request): Promise<Response> {
const { searchParams } = new URL(request.url);
let endpoint = searchParams.get("endpoint");
const result = await (async () => {
if (endpoint === "gh") return await callGitHub();
if (endpoint === "swapi") return await callSwapi();
return "Add an endpoint in the form of either '?endpoint=gh' or '?endpoint=swapi'!";
})();
return end(result);
},
};
/**
* @description Convenience wrapper for fetching data from GitHub.
*/
async function callGitHub() {
return await fetchData(
"https://api.github.com/repos/facebook/react/stats/participation",
{
headers: {
Accept: "application/vnd.github.v3+json",
"User-Agent": "GitHub API Client for Cloudflare Workers"
},
}
);
}
/**
* @description Convenience wrapper for fetching data from SW API.
*/
async function callSwapi() {
return await fetchData("https://swapi.dev/api/people/1");
}
/**
* @description Handle fetching data.
*/
async function fetchData(url: string, options?: Record<string, any>) {
return fetch(url, {
method: "GET",
...(options || {}),
})
.then((res: any) => {
console.log("Status:", res.status);
console.log("Headers:", JSON.stringify(Object.fromEntries(res.headers)));
if (res.status === 200) return res.json();
return "";
})
.catch((error: any) => {
console.error(error);
return error?.message || "Unknown error";
});
}
/**
* @description Send back JSON response.
*/
function end(result: string | Record<string, any>) {
const json = JSON.stringify(
{
result,
},
null,
2
);
return new Response(json, {
headers: {
"Content-Type": "application/json",
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment