Skip to content

Instantly share code, notes, and snippets.

@mizchi
Last active January 8, 2021 04:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizchi/119e8c2a348964f9c57149a660035a46 to your computer and use it in GitHub Desktop.
Save mizchi/119e8c2a348964f9c57149a660035a46 to your computer and use it in GitHub Desktop.
/* How to use
import { getTypes } from "../api/types"
const result = await getTypes("https://esm.sh/react");
if (result.hasTypes) {
console.log(result.typesCode);
}
*/
import { NextApiHandler } from "next";
import fetch from "isomorphic-unfetch";
type GetTypesResponse =
| {
hasTypes: true;
typesUrl: string;
typesCode: string;
}
| {
hasTypes: false;
};
const handler: NextApiHandler<GetTypesResponse> = async (req, res) => {
const b64 = req.query["b64"] as string;
const codeUrl = Buffer.from(b64, "base64").toString("utf-8");
try {
const response = await fetch(codeUrl);
const typesUrl = response.headers.get("x-typescript-types") as string;
if (typesUrl == null) {
return res.json({ hasTypes: false });
}
const typesCode = await fetch(typesUrl).then((res) => {
return res.text();
});
res.json({ typesUrl, typesCode, hasTypes: true });
} catch (err) {
res.status(400).end();
}
};
export default handler;
export async function getTypes(url: string): Promise<GetTypesResponse> {
const encoded = btoa(url);
return fetch(`/api/types/${encoded}`).then((res) => res.json());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment