| 1 | const cache: { [key: string]: Promise<string> } = {}; |
| 2 | |
| 3 | export async function highlightCode( |
| 4 | input: string, |
| 5 | language?: string |
| 6 | ): Promise<string> { |
| 7 | if (!!cache[input]) { |
| 8 | return cache[input]; |
| 9 | } |
| 10 | try { |
| 11 | const promise = fetch('/api/highlight', { |
| 12 | method: 'POST', |
| 13 | headers: { 'Content-Type': 'application/json' }, |
| 14 | body: JSON.stringify({ input, language }), |
| 15 | }) |
| 16 | .then((response) => response.json()) |
| 17 | .then(({ output }) => output); |
| 18 | cache[input] = promise; |
| 19 | return promise; |
| 20 | } catch (exception) { |
| 21 | console.error(exception); |
| 22 | return input; |
| 23 | } |
| 24 | } |