[BUG][Javascript] paramToString does not handle non-primitives
Created by: tray2100
Description
It looks like the when an API call is being constructed, the params are passed through a generic paramToString
function defined here that looks like this:
exports.prototype.paramToString = function (param) {
if (param == undefined || param == null) {
return '';
}
if (param instanceof Date) {
return param.toJSON();
}
return param.toString();
};
This breaks if any of your parameters are not primitives because param.toString()
will transform it into [object Object]
.
openapi-generator version
4.3.1 ... doesn't look to be a regression. Just missing handling
OpenAPI declaration file content or url
/someOperation:
post:
requestBody:
description: "POST request that uploads a file and takes in a metadata object"
content:
multipart/form-data:
schema:
type: "object"
properties:
metadata:
$ref: "#/components/schemas/SomeType"
file:
format: "binary"
type: "string"
encoding:
metadata:
contentType: "application/json"
Steps to reproduce
Invoke any POST operation where one parameter is a complex type (Object) using this client and the service will receive [object Object]
as a value for the parameter.
Related issues/PRs
Similar issues:
Suggest a fix
I believe the fix should be to, as a last step, see if the parameter can be JSON-ified. If it can be, we should run JSON.stringify() on it and use that result instead of the output of param.toString()
. I think a simple method like this would suffice:
exports.prototype.canBeJsonified = function(str) {
if (typeof str !== 'string' && typeof str !== 'object') return false;
try {
const type = str.toString();
return type === '[object Object]'
|| type === '[object Array]';
} catch (err) {
return false;
}
};
and we update the paramToString method to be
exports.prototype.paramToString = function(param) {
if (param == undefined || param == null) {
return '';
}
if (param instanceof Date) {
return param.toJSON();
}
if (this.canBeJsonified(param)) {
return JSON.stringify(param);
}
return param.toString();
};
cc @CodeNinjai @frol @cliffano @wing328