11import ts from "typescript" ;
2- import { MethodDeclaration } from "ts-morph" ;
2+ import { MethodDeclaration , Type } from "ts-morph" ;
33import {
44 BuildCommonTypeName ,
55 capitalizeFirstLetter ,
@@ -72,26 +72,33 @@ export const createApiResponseType = ({
7272 } ;
7373} ;
7474
75+ /**
76+ * Replace the import("...") surrounding the type if there is one.
77+ * This can happen when the type is imported from another file, but
78+ * we are already importing all the types from that file.
79+ */
80+ function getShortType ( type : string ) {
81+ return type . replaceAll ( / i m p o r t \( " [ a - z A - Z \/ \. - ] * " \) \. / g, "" ) ;
82+ }
83+
7584export function getRequestParamFromMethod ( method : MethodDeclaration ) {
7685 if ( ! method . getParameters ( ) . length ) {
7786 return null ;
7887 }
7988
80- // we need to get the properties of the object
81-
8289 const params = method
8390 . getParameters ( )
8491 . map ( ( param ) => {
8592 const paramNodes = extractPropertiesFromObjectParam ( param ) ;
8693 return paramNodes . map ( ( refParam ) => ( {
8794 name : refParam . name ,
88- typeName : refParam . type . getText ( ) ,
95+ typeName : getShortType ( refParam . type . getText ( ) ) ,
8996 optional : refParam . optional ,
9097 } ) ) ;
9198 } )
9299 . flat ( ) ;
93100
94- const areAllOptional = params . every ( ( param ) => param . optional ) ;
101+ const areAllPropertiesOptional = params . every ( ( param ) => param . optional ) ;
95102
96103 return ts . factory . createParameterDeclaration (
97104 undefined ,
@@ -118,11 +125,17 @@ export function getRequestParamFromMethod(method: MethodDeclaration) {
118125 // param.hasQuestionToken() ?? param.getInitializer()?.compilerNode
119126 // ? ts.factory.createToken(ts.SyntaxKind.QuestionToken)
120127 // : param.getQuestionTokenNode()?.compilerNode,
121- ts . factory . createTypeReferenceNode ( refParam . typeName )
128+ ts . factory . createTypeReferenceNode (
129+ ts . factory . createIdentifier ( refParam . typeName )
130+ )
122131 ) ;
123132 } )
124133 ) ,
125- areAllOptional ? ts . factory . createObjectLiteralExpression ( ) : undefined
134+ // if all params are optional, we create an empty object literal
135+ // so the hook can be called without any parameters
136+ areAllPropertiesOptional
137+ ? ts . factory . createObjectLiteralExpression ( )
138+ : undefined
126139 ) ;
127140}
128141
0 commit comments