11import type { GlobalContext , OperationObject , ParameterObject , PathItemObject } from "../types.js" ;
2- import { comment , tsReadonly } from "../utils.js" ;
2+ import { comment , tsReadonly , nodeType } from "../utils.js" ;
33import { transformOperationObj } from "./operation.js" ;
44import { transformParametersArray } from "./parameters.js" ;
55
@@ -8,6 +8,24 @@ interface TransformPathsObjOption extends GlobalContext {
88 operations : Record < string , { operation : OperationObject ; pathItem : PathItemObject } > ;
99}
1010
11+ const httpMethods = [ "get" , "put" , "post" , "delete" , "options" , "head" , "patch" , "trace" ] as const ;
12+
13+ function replacePathParamsWithTypes ( url : string , params : NonNullable < PathItemObject [ "parameters" ] > ) {
14+ let result = url ;
15+
16+ params . forEach ( ( param ) => {
17+ if ( "in" in param && param . in === "path" ) {
18+ if ( param . schema && "type" in param . schema ) {
19+ result = result . replace ( `{${ param . name } }` , `\${${ nodeType ( param . schema ) } }` ) ;
20+ } else if ( param . type ) {
21+ result = result . replace ( `{${ param . name } }` , `\${${ nodeType ( { type : param . type } ) } }` ) ;
22+ }
23+ }
24+ } ) ;
25+
26+ return result ;
27+ }
28+
1129/** Note: this needs to mutate objects passed in */
1230export function transformPathsObj ( paths : Record < string , PathItemObject > , options : TransformPathsObjOption ) : string {
1331 const { globalParameters, operations, ...ctx } = options ;
@@ -23,10 +41,30 @@ export function transformPathsObj(paths: Record<string, PathItemObject>, options
2341 continue ;
2442 }
2543
26- output += ` ${ readonly } "${ url } ": {\n` ; // open PathItem
44+ let key = `"${ url } "` ;
45+
46+ if ( url . includes ( "{" ) && url . includes ( "}" ) && ctx . pathParamsAsTypes ) {
47+ let params ;
48+
49+ if ( pathItem . parameters ) {
50+ params = pathItem . parameters ;
51+ } else {
52+ const firstMethodParams = Object . values ( pathItem )
53+ . map ( ( props ) => typeof props === "object" && props . parameters )
54+ . filter ( Boolean ) [ 0 ] ;
55+
56+ if ( firstMethodParams ) {
57+ params = firstMethodParams ;
58+ }
59+ }
60+
61+ key = `[key: \`${ replacePathParamsWithTypes ( url , params ) } \`]` ;
62+ }
63+
64+ output += ` ${ readonly } ${ key } : {\n` ; // open PathItem
2765
2866 // methods
29- for ( const method of [ "get" , "put" , "post" , "delete" , "options" , "head" , "patch" , "trace" ] ) {
67+ for ( const method of httpMethods ) {
3068 const operation = ( pathItem as any ) [ method ] ;
3169 if ( ! operation ) continue ; // only allow valid methods
3270 if ( operation . description ) output += comment ( operation . description ) ; // add comment
0 commit comments