|
| 1 | +import { basename } from "node:path"; |
| 2 | + |
| 3 | +import type { Chunk, OperationChunk } from "../types/chunk.ts"; |
| 4 | +import type { |
| 5 | + CodeSamplesResponse, |
| 6 | + CodeSnippet, |
| 7 | + ErrorResponse, |
| 8 | +} from "../types/codeSnippet.ts"; |
| 9 | +import { getSettings } from "./settings.ts"; |
| 10 | + |
| 11 | +const CODE_SNIPPETS_API_URL = "http://localhost:35290"; |
| 12 | + |
| 13 | +export type DocsCodeSnippets = Record<OperationChunk["id"], CodeSnippet>; |
| 14 | + |
| 15 | +export const generateDocsCodeSnippets = async ( |
| 16 | + docsData: Map<string, Chunk>, |
| 17 | + specContents: string |
| 18 | +): Promise<DocsCodeSnippets> => { |
| 19 | + const { spec, tryItNow } = getSettings(); |
| 20 | + if (!tryItNow) { |
| 21 | + return {}; |
| 22 | + } |
| 23 | + |
| 24 | + const docsCodeSnippets: DocsCodeSnippets = {}; |
| 25 | + |
| 26 | + const specFilename = basename(spec); |
| 27 | + // create a by operationId map of the operation chunks |
| 28 | + const operationChunksByOperationId = new Map<string, OperationChunk>(); |
| 29 | + for (const chunk of docsData.values()) { |
| 30 | + if (chunk.chunkType === "operation") { |
| 31 | + operationChunksByOperationId.set(chunk.chunkData.operationId, chunk); |
| 32 | + } |
| 33 | + } |
| 34 | + try { |
| 35 | + const formData = new FormData(); |
| 36 | + |
| 37 | + const blob = new Blob([specContents]); |
| 38 | + formData.append("language", "typescript"); |
| 39 | + formData.append("schema_file", blob, specFilename); |
| 40 | + formData.append("package_name", tryItNow.npmPackageName); |
| 41 | + formData.append("sdk_class_name", tryItNow.sdkClassName); |
| 42 | + |
| 43 | + const res = await fetch(`${CODE_SNIPPETS_API_URL}/v1/code_sample/preview`, { |
| 44 | + method: "POST", |
| 45 | + body: formData, |
| 46 | + }); |
| 47 | + |
| 48 | + const json = (await res.json()) as unknown; |
| 49 | + |
| 50 | + if (!res.ok) { |
| 51 | + const error = json as ErrorResponse; |
| 52 | + throw new Error(`Failed to generate code sample: ${error.message}`); |
| 53 | + } |
| 54 | + const codeSnippets = (json as CodeSamplesResponse).snippets; |
| 55 | + |
| 56 | + for (const snippet of codeSnippets) { |
| 57 | + const chunk = operationChunksByOperationId.get(snippet.operationId); |
| 58 | + // only set the usage snippet if the operation id exists in the spec |
| 59 | + if (chunk) { |
| 60 | + docsCodeSnippets[chunk.id] = snippet; |
| 61 | + } |
| 62 | + } |
| 63 | + } catch (error) { |
| 64 | + console.error("There was an error generating code snippets", error); |
| 65 | + return {}; |
| 66 | + } |
| 67 | + return docsCodeSnippets; |
| 68 | +}; |
0 commit comments