|
1
|
import { getCloudflareContext } from "@opennextjs/cloudflare" |
|
2
|
|
|
3
|
/** |
|
4
|
* Reads a spec file through the R2 bucket binding, avoiding the HTTP round |
|
5
|
* trip that fetching the public bucket URL requires. The URL's pathname maps |
|
6
|
* directly to the object key because the public bucket URL serves the bucket |
|
7
|
* root. Returns null outside Cloudflare (next dev / build), when the binding |
|
8
|
* isn't configured, or when `url` isn't an R2 URL, so callers can fall back |
|
9
|
* to fetching or reading from the filesystem. |
|
10
|
*/ |
|
11
|
export async function readSpecFromBinding(url: string): Promise<string | null> { |
|
12
|
const r2Base = process.env.SPECS_R2_BASE_URL |
|
13
|
if (!r2Base || !url.startsWith(r2Base)) { |
|
14
|
return null |
|
15
|
} |
|
16
|
|
|
17
|
try { |
|
18
|
// async mode so this also works in statically rendered contexts |
|
19
|
const { env } = await getCloudflareContext({ async: true }) |
|
20
|
const key = new URL(url).pathname.replace(/^\//, "") |
|
21
|
const object = await env.SPECS_R2_BUCKET?.get(key) |
|
22
|
return object ? await object.text() : null |
|
23
|
} catch { |
|
24
|
return null |
|
25
|
} |
|
26
|
} |