|
1
|
import { NextResponse } from "next/server" |
|
2
|
import path from "path" |
|
3
|
import OpenAPIParser from "@readme/openapi-parser" |
|
4
|
import getPathsOfTag from "@/utils/get-paths-of-tag" |
|
5
|
import type { OpenAPI } from "types" |
|
6
|
import { withRouteErrorHandling, workerCompatibleFetch } from "docs-utils" |
|
7
|
import { parse as parseYaml } from "yaml" |
|
8
|
import { readSpecFromBinding } from "@/utils/read-spec-from-binding" |
|
9
|
|
|
10
|
export const GET = withRouteErrorHandling(async (request: Request) => { |
|
11
|
const { searchParams } = new URL(request.url) |
|
12
|
const area = searchParams.get("area") |
|
13
|
const expand = searchParams.get("expand") |
|
14
|
if (area !== "admin" && area !== "store") { |
|
15
|
return NextResponse.json( |
|
16
|
{ |
|
17
|
success: false, |
|
18
|
message: `area ${area} is not allowed`, |
|
19
|
}, |
|
20
|
{ |
|
21
|
status: 400, |
|
22
|
} |
|
23
|
) |
|
24
|
} |
|
25
|
const r2Base = process.env.SPECS_R2_BASE_URL |
|
26
|
const specPath = r2Base |
|
27
|
? `${r2Base}/specs/${area}/openapi.yaml` |
|
28
|
: path.join(process.cwd(), "specs", area, "openapi.yaml") |
|
29
|
const specsFromBinding = await readSpecFromBinding(specPath) |
|
30
|
const baseSpecs = specsFromBinding |
|
31
|
? ((await parseYaml(specsFromBinding)) as OpenAPI.ExpandedDocument) |
|
32
|
: await workerCompatibleFetch<OpenAPI.ExpandedDocument>({ |
|
33
|
url: specPath, |
|
34
|
responseTransformer: async (res) => { |
|
35
|
if (!res.ok) { |
|
36
|
throw new Error(`Failed to fetch spec: ${specPath} (${res.status})`) |
|
37
|
} |
|
38
|
const text = await res.text() |
|
39
|
return (await parseYaml(text)) as OpenAPI.ExpandedDocument |
|
40
|
}, |
|
41
|
fallbackAction: async () => { |
|
42
|
// In local development, we can read the spec directly from the filesystem |
|
43
|
return (await OpenAPIParser.parse( |
|
44
|
specPath |
|
45
|
)) as OpenAPI.ExpandedDocument |
|
46
|
}, |
|
47
|
}) |
|
48
|
|
|
49
|
if (expand) { |
|
50
|
const paths = await getPathsOfTag(expand, area) |
|
51
|
if (paths) { |
|
52
|
baseSpecs.expandedTags = {} |
|
53
|
baseSpecs.expandedTags[expand] = paths.paths |
|
54
|
} |
|
55
|
} |
|
56
|
|
|
57
|
return NextResponse.json(baseSpecs, { |
|
58
|
status: 200, |
|
59
|
}) |
|
60
|
}) |