Skip to content

Commit 5c9f891

Browse files
committed
feat(code-gen): include validators when targetting Node.js with ts-axios
1 parent 8ed5778 commit 5c9f891

File tree

1 file changed

+50
-2
lines changed

1 file changed

+50
-2
lines changed

packages/code-gen/src/api-client/ts-axios.js

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,14 @@ export function tsAxiosGetApiClientFile(generateContext, route) {
174174
typeImportCollector.destructure("axios", "AxiosInstance");
175175
}
176176

177+
if (
178+
generateContext.options.generators.apiClient?.target.targetRuntime ===
179+
"node.js"
180+
) {
181+
importCollector.destructure("@compas/stdlib", "AppError");
182+
importCollector.raw(`import FormData from "form-data";`);
183+
}
184+
177185
return file;
178186
}
179187

@@ -220,7 +228,17 @@ export function tsAxiosGenerateFunction(
220228
}
221229

222230
// Allow overwriting any request config
223-
args.push(`requestConfig?: AxiosRequestConfig`);
231+
if (
232+
generateContext.options.generators.apiClient?.target.targetRuntime ===
233+
"node.js" &&
234+
route.response
235+
) {
236+
args.push(
237+
`requestConfig?: AxiosRequestConfig & { skipResponseValidation?: boolean }`,
238+
);
239+
} else {
240+
args.push(`requestConfig?: AxiosRequestConfig`);
241+
}
224242

225243
fileContextRemoveLinePrefix(file, 3);
226244
fileWrite(file, ` */`);
@@ -336,7 +354,37 @@ export function tsAxiosGenerateFunction(
336354
fileContextSetIndent(file, -1);
337355
fileWrite(file, `});`);
338356

339-
fileWrite(file, `return response.data;`);
357+
if (
358+
route.response &&
359+
generateContext.options.generators.apiClient?.target.targetRuntime ===
360+
"node.js"
361+
) {
362+
fileBlockStart(file, `if (requestConfig?.skipResponseValidation)`);
363+
fileWrite(file, `return response.data;`);
364+
fileBlockEnd(file);
365+
366+
fileWrite(
367+
file,
368+
`const { value, error } = ${contextNames.responseValidator}(response.data);`,
369+
);
370+
fileBlockStart(file, `if (error)`);
371+
372+
fileWrite(
373+
file,
374+
`throw AppError.validationError("validator.error", {
375+
route: { group: "${route.group}", name: "${route.name}", },
376+
error,
377+
});`,
378+
);
379+
380+
fileBlockEnd(file);
381+
382+
fileBlockStart(file, `else`);
383+
fileWrite(file, `return value;`);
384+
fileBlockEnd(file);
385+
} else {
386+
fileWrite(file, `return response.data;`);
387+
}
340388

341389
fileBlockEnd(file);
342390

0 commit comments

Comments
 (0)