我正在尝试使用 Javascript 插件在 Workato 中构建 API 端点。部分要求是根据我定义的模式验证 JSON 请求是否有效。
具体来说,如果未提供必填字段或提供的值与预期的数据类型不匹配(例如,预期数字时的字符串),我需要抛出 400 Bad Request 错误。
我最初的想法是定义一个“checkRequest”函数,该函数将使用每个可能的数据点接收 JSON 请求对象,并基本上通过一个巨大的 if/else if /else 条件列表来测试“null”的每个值并使用“type of" 来测试数据类型,如果遇到错误则返回。
但是,请注意,该架构非常庞大,包含大约 100 个不同的数据点,并且由对象内的嵌套对象组成,因此我希望找到最优化的迭代方式,而不是依赖大量的 if 语句。
请参阅下面的代码和基于架构的请求片段(无法共享完整架构):
我的代码:
function checkRequest({
partner_id,
merchant_reference_id,
optional_string,
}) {
let response = {
validRequest: true,
responseStatus: "",
errorTitle: "",
errorDetail: "",
errorCode: "",
};
let badRequestTitle = "Bad Request";
let requiredFieldErrorDetail = (field) => {
return field + " is a required field but was not provided in request.";
};
let wrongFormatErrorDetailDetail = (field, inputDataType, expectedDataType) =>
field +
" expected data type is " +
expectedDataType +
", but " +
inputDataType +
" was received.";
//partner_id
if (partner_id == "" || partner_id == null) {
response.validRequest = false;
response.errorDetail = requiredFieldErrorDetail("partnerID");
console.log(response);
return response;
} else if (typeof partner_id != "string") {
response.validRequest = false;
response.responseStatus = "400";
response.errorCode = "40001";
response.errorTitle = badRequestTitle;
response.errorDetail = wrongFormatErrorDetail(
"partnerID",
typeof partner_id,
"string"
);
console.log(response);
return response;
}
//merchant_reference_ID
else if (merchant_reference_id == "" || merchant_reference_id == null) {
response.validRequest = false;
response.errorDetail = requiredFieldErrorDetail("partnerID");
console.log(response);
return response;
} else if (typeof merchant_reference_id != "string") {
response.validRequest = false;
response.responseStatus = "400";
response.errorCode = "40001";
response.errorTitle = badRequestTitle;
response.errorDetail = wrongFormatErrorDetail(
"partnerID",
typeof merchant_reference_id,
"string"
);
console.log(response);
return response;
}
//else
else {
console.log(response);
return response;
}
}
let requestBody = {
partner_id: "",
merchant_reference_id: "aa",
optional_string: "3",
};
checkRequest(requestBody);
示例请求片段(假设某些字段是必需的,而其他字段是可选的):
{
"application": {
"partnerReferral": {
"partnerID": "mg3e09f8-a8dd-44e6-bb06-55293b799318",
"merchantReferenceID": "mg3e09f8a8dd44e6bb06-55293b799318"
},
"businessInformation": {
"identity": [
{
"identifier": "EMPLOYER_IDENTIFICATION_NUMBER",
"value": "77-1122333"
}
],
"businessType": "ASSOCIATION",
"classification": {
"code": "SIC",
"value": "string"
}
}
}
}
希望依靠 vanilla Javascript 来实现这一点是最好的方法,但如果需要,可以使用插件。