|
1 | 1 | import ts from "typescript"; |
2 | | -import { MethodDeclaration } from "ts-morph"; |
| 2 | +import { MethodDeclaration, Type } from "ts-morph"; |
3 | 3 | import { |
4 | 4 | BuildCommonTypeName, |
5 | 5 | capitalizeFirstLetter, |
@@ -72,26 +72,33 @@ export const createApiResponseType = ({ |
72 | 72 | }; |
73 | 73 | }; |
74 | 74 |
|
| 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(/import\("[a-zA-Z\/\.-]*"\)\./g, ""); |
| 82 | +} |
| 83 | + |
75 | 84 | export function getRequestParamFromMethod(method: MethodDeclaration) { |
76 | 85 | if (!method.getParameters().length) { |
77 | 86 | return null; |
78 | 87 | } |
79 | 88 |
|
80 | | - // we need to get the properties of the object |
81 | | - |
82 | 89 | const params = method |
83 | 90 | .getParameters() |
84 | 91 | .map((param) => { |
85 | 92 | const paramNodes = extractPropertiesFromObjectParam(param); |
86 | 93 | return paramNodes.map((refParam) => ({ |
87 | 94 | name: refParam.name, |
88 | | - typeName: refParam.type.getText(), |
| 95 | + typeName: getShortType(refParam.type.getText()), |
89 | 96 | optional: refParam.optional, |
90 | 97 | })); |
91 | 98 | }) |
92 | 99 | .flat(); |
93 | 100 |
|
94 | | - const areAllOptional = params.every((param) => param.optional); |
| 101 | + const areAllPropertiesOptional = params.every((param) => param.optional); |
95 | 102 |
|
96 | 103 | return ts.factory.createParameterDeclaration( |
97 | 104 | undefined, |
@@ -122,7 +129,11 @@ export function getRequestParamFromMethod(method: MethodDeclaration) { |
122 | 129 | ); |
123 | 130 | }) |
124 | 131 | ), |
125 | | - areAllOptional ? ts.factory.createObjectLiteralExpression() : undefined |
| 132 | + // if all params are optional, we create an empty object literal |
| 133 | + // so the hook can be called without any parameters |
| 134 | + areAllPropertiesOptional |
| 135 | + ? ts.factory.createObjectLiteralExpression() |
| 136 | + : undefined |
126 | 137 | ); |
127 | 138 | } |
128 | 139 |
|
|
0 commit comments