forked from microsoft/TypeScript-Website
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetExample.ts
More file actions
36 lines (32 loc) · 1.15 KB
/
getExample.ts
File metadata and controls
36 lines (32 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
export const getExampleSourceCode = async (prefix: string, lang: string, exampleID: string) => {
try {
const site = `${document.location.protocol}//${document.location.host}${prefix}`
const examplesTOCHref = `${site}/js/examples/${lang}.json`
const res = await fetch(examplesTOCHref)
if (!res.ok) {
console.error("Could not fetch example TOC for lang: " + lang)
return {}
}
const toc = await res.json()
const example = toc.examples.find((e: any) => e.id === exampleID)
if (!example) {
// prettier-ignore
console.error(`Could not find example with id: ${exampleID} in\n// ${document.location.protocol}//${document.location.host}${examplesTOCHref}`)
return {}
}
const exampleCodePath = `${site}/js/examples/${example.lang}/${example.path.join("/")}/${example.name}`
const codeRes = await fetch(exampleCodePath)
let code = await codeRes.text()
// Handle removing the compiler settings stuff
if (code.startsWith("//// {")) {
code = code.split("\n").slice(1).join("\n").trim()
}
return {
example,
code,
}
} catch (e) {
console.log(e)
return {}
}
}