Skip to content

Instantly share code, notes, and snippets.

@mizchi

mizchi/pages_api_[b64].ts

Last active Jan 8, 2021
Embed
What would you like to do?
/* 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