|
1 |
| -import type { GlobalContext, PathsObject } from "../types.js"; |
| 1 | +import type { GlobalContext, PathsObject, PathItemObject, ParameterObject, ReferenceObject, OperationObject } from "../types.js"; |
2 | 2 | import { escStr, getEntries, indent } from "../utils.js";
|
3 | 3 | import transformParameterObject from "./parameter-object.js";
|
4 | 4 | import transformPathItemObject from "./path-item-object.js";
|
5 | 5 |
|
| 6 | +const OPERATIONS = ["get", "post", "put", "delete", "options", "head", "patch", "trace"]; |
| 7 | + |
| 8 | +function extractPathParams(obj?: ReferenceObject | PathItemObject | OperationObject | undefined): Map<string, ParameterObject> { |
| 9 | + const params = new Map(); |
| 10 | + obj && |
| 11 | + "parameters" in obj && |
| 12 | + obj.parameters?.forEach((p) => { |
| 13 | + if ("in" in p && p.in === "path") { |
| 14 | + params.set(p.name, p); |
| 15 | + } |
| 16 | + }); |
| 17 | + return params; |
| 18 | +} |
| 19 | + |
6 | 20 | export default function transformPathsObject(pathsObject: PathsObject, ctx: GlobalContext): string {
|
7 | 21 | let { indentLv } = ctx;
|
8 | 22 | const output: string[] = ["{"];
|
9 | 23 | indentLv++;
|
10 | 24 | for (const [url, pathItemObject] of getEntries(pathsObject, ctx.alphabetize, ctx.excludeDeprecated)) {
|
11 | 25 | let path = url;
|
12 | 26 |
|
| 27 | + const pathParams = new Map([...extractPathParams(pathItemObject), ...OPERATIONS.flatMap((op) => Array.from(extractPathParams(pathItemObject[op as keyof PathItemObject])))]); |
| 28 | + |
13 | 29 | // build dynamic string template literal index
|
14 |
| - if (ctx.pathParamsAsTypes && pathItemObject.parameters) { |
15 |
| - for (const p of pathItemObject.parameters) { |
16 |
| - if ("in" in p && p.in === "path") { |
17 |
| - const paramType = transformParameterObject(p, { path: `#/paths/${url}/parameters/${p.name}`, ctx }); |
18 |
| - path = path.replace(`{${p.name}}`, `\${${paramType}}`); |
19 |
| - } |
| 30 | + if (ctx.pathParamsAsTypes && pathParams) { |
| 31 | + for (const p of pathParams.values()) { |
| 32 | + const paramType = transformParameterObject(p, { path: `#/paths/${url}/parameters/${p.name}`, ctx }); |
| 33 | + path = path.replace(`{${p.name}}`, `\${${paramType}}`); |
20 | 34 | }
|
21 | 35 | path = `[path: \`${path}\`]`;
|
22 | 36 | } else {
|
|
0 commit comments