Last active
January 8, 2021 04:53
-
-
Save mizchi/119e8c2a348964f9c57149a660035a46 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
/* 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