Explorar o código

[*]优化requestBody属性校验,优化swagger文档

Lianjy %!s(int64=4) %!d(string=hai) anos
pai
achega
c5346295d1

+ 18 - 7
magic-api/src/main/java/org/ssssssss/magicapi/controller/RequestHandler.java

@@ -2,6 +2,7 @@ package org.ssssssss.magicapi.controller;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
 import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.ObjectUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -113,21 +114,23 @@ public class RequestHandler extends MagicController {
 		if (context.get(VAR_NAME_REQUEST_BODY) != null && StringUtils.isNotBlank(requestEntity.getApiInfo().getRequestBody()) && JsonUtils.readValue(requestEntity.getApiInfo().getRequestBody(), BaseDefinition.class).getChildren().size() > 0) {
 			// 验证 body
 			BaseDefinition body = JsonUtils.readValue(requestEntity.getApiInfo().getRequestBody(), BaseDefinition.class);
+			Object bodyValue = ObjectUtils.clone(context.get(VAR_NAME_REQUEST_BODY));
+
 			// 请求体首层是数组的时候单独处理
-            if (context.get(VAR_NAME_REQUEST_BODY) instanceof List) {
+            if (bodyValue instanceof List) {
 				if (!VAR_NAME_REQUEST_BODY_VALUE_TYPE_ARRAY.equalsIgnoreCase(body.getDataType().getJavascriptType())) {
                     Object result = resultProvider.buildResult(requestEntity, RESPONSE_CODE_INVALID, String.format("body参数错误,应为[%s]", body.getDataType().getJavascriptType()));
                     return requestEntity.isRequestedFromTest() ? new JsonBean<>(BODY_INVALID, result) : result;
 				}
 
-				for (Object objMap : (List)context.get(VAR_NAME_REQUEST_BODY)) {
-					value = doValidate(requestEntity, VAR_NAME_REQUEST_BODY, body.getChildren().get(0).getChildren(), (Map)objMap);
+				for (Map valueMap : (List<Map>)bodyValue) {
+					value = doValidate(requestEntity, VAR_NAME_REQUEST_BODY, body.getChildren().get(0).getChildren(), ObjectUtils.clone(valueMap));
 					if (value != null) {
 						return requestEntity.isRequestedFromTest() ? new JsonBean<>(BODY_INVALID, value) : value;
 					}
 				}
 			} else {
-				value = doValidate(requestEntity, VAR_NAME_REQUEST_BODY, body.getChildren(), (Map)context.get(VAR_NAME_REQUEST_BODY));
+				value = doValidate(requestEntity, VAR_NAME_REQUEST_BODY, body.getChildren(), (Map)bodyValue);
 				if (value != null) {
 					return requestEntity.isRequestedFromTest() ? new JsonBean<>(BODY_INVALID, value) : value;
 				}
@@ -159,14 +162,22 @@ public class RequestHandler extends MagicController {
 
 			// 针对requestBody多层级的情况
 			if (VAR_NAME_REQUEST_BODY_VALUE_TYPE_OBJECT.equalsIgnoreCase(parameter.getDataType().getJavascriptType())) {
-				Object result = doValidate(requestEntity, VAR_NAME_REQUEST_BODY, parameter.getChildren(), (Map)parameters.get(parameter.getName()));
+				Map map = (Map)parameters.get(parameter.getName());
+				Object result = doValidate(requestEntity, VAR_NAME_REQUEST_BODY, parameter.getChildren(), map);
 				if (result != null) {
 					return result;
 				}
 			}
+
             if (VAR_NAME_REQUEST_BODY_VALUE_TYPE_ARRAY.equalsIgnoreCase(parameter.getDataType().getJavascriptType())) {
-                for (Object objMap : (List)parameters.get(parameter.getName())) {
-					Object result = doValidate(requestEntity, VAR_NAME_REQUEST_BODY, parameter.getChildren().get(0).getChildren(), (Map)objMap);
+            	if (parameters == null || parameters.get(parameter.getName()) == null) {
+					return resultProvider.buildResult(requestEntity, RESPONSE_CODE_INVALID, StringUtils.defaultIfBlank(parameter.getError(), String.format("%s[%s]为必填项", comment, parameter.getName())));
+				}
+				if (!(parameters.get(parameter.getName()) instanceof List)) {
+					return resultProvider.buildResult(requestEntity, RESPONSE_CODE_INVALID, StringUtils.defaultIfBlank(parameter.getError(), String.format("%s[%s]数据类型错误", comment, parameter.getName())));
+				}
+                for (Map valueMap : (List<Map>)parameters.get(parameter.getName())) {
+					Object result = doValidate(requestEntity, VAR_NAME_REQUEST_BODY, parameter.getChildren().get(0).getChildren(), ObjectUtils.clone(valueMap));
 					if (result != null) {
 						return result;
 					}

+ 2 - 2
magic-api/src/main/java/org/ssssssss/magicapi/model/ApiInfo.java

@@ -152,7 +152,7 @@ public class ApiInfo extends MagicEntity {
 				.flatMap(it -> it.getOptions().stream())
 				.forEach(option -> {
 					if (!map.containsKey(option.getName())) {
-						map.put(option.getName(), option.getValue().toString());
+						map.put(option.getName(), String.valueOf(option.getValue()));
 					}
 				});
 		return map;
@@ -229,7 +229,7 @@ public class ApiInfo extends MagicEntity {
 				.filter(it -> key.equals(it.getName()))
 				.findFirst()
 				.map(it -> {
-					return String.valueOf(it.getValue());
+					return Objects.toString(it.getValue(), null);
 				}).orElse(null);
 	}
 

+ 3 - 3
magic-api/src/main/java/org/ssssssss/magicapi/swagger/SwaggerProvider.java

@@ -130,7 +130,7 @@ public class SwaggerProvider {
 					String groupName = groupServiceProvider.getFullName(info.getGroupId()).replace("/", "-");
 					String voName =  groupName + "«" + info.getPath().replaceFirst("/", "").replaceAll("/", "_") + "«";
 					if (VAR_NAME_REQUEST_BODY_VALUE_TYPE_ARRAY.equalsIgnoreCase(baseDefinition.getDataType().getJavascriptType())) {
-						voName += StringUtils.defaultIfBlank(baseDefinition.getChildren().get(0).getName(), StringUtils.defaultIfBlank(baseDefinition.getName(), VAR_NAME_REQUEST_BODY_VALUE_TYPE_ARRAY)) + "»»";
+						voName += StringUtils.defaultIfBlank(baseDefinition.getChildren().get(0).getName(), VAR_NAME_REQUEST_BODY + "_" + StringUtils.defaultIfBlank(baseDefinition.getName(), VAR_NAME_REQUEST_BODY_VALUE_TYPE_ARRAY)) + "»»";
 					} else {
 						voName += StringUtils.defaultIfBlank(baseDefinition.getName(), VAR_NAME_REQUEST_BODY) + "»»";
 					}
@@ -153,7 +153,7 @@ public class SwaggerProvider {
         result.put("description", target.getDescription());
         if (VAR_NAME_REQUEST_BODY_VALUE_TYPE_ARRAY.equalsIgnoreCase(target.getDataType().getJavascriptType())) {
             if (target.getChildren().size() > 0) {
-                result.put("items", doProcessDefinition(target.getChildren().get(0), info, parentName + "_" +target.getName()));
+                result.put("items", doProcessDefinition(target.getChildren().get(0), info, parentName + "_" + StringUtils.defaultIfBlank(target.getName(), VAR_NAME_REQUEST_BODY_VALUE_TYPE_ARRAY)));
             } else {
                 result.put("items", Collections.emptyList());
             }
@@ -163,7 +163,7 @@ public class SwaggerProvider {
             String voName = groupName + "«" + info.getPath().replaceFirst("/", "").replaceAll("/", "_") + "«" + StringUtils.defaultIfBlank(target.getName(), parentName)  + "»»";
             if (this.DEFINITION_MAP.containsKey(voName)) {
 				// TODO 应该不会出现名字都一样的
-				voName.replace("»»", parentName + "»»");
+				voName.replace("»»", "_" + parentName + "»»");
 			}
             result.put("originalRef", voName);
             result.put("$ref", DEFINITION + voName);

+ 1 - 1
magic-editor/src/console/src/components/common/magic-json-tree.vue

@@ -13,7 +13,7 @@
 
           {{item.level > 0 ? item.name : ''}}{{item.dataType != 'Object' && item.dataType != 'Array' ? ':' : ''}}
           <span :style="item.dataType | color">
-              {{item.dataType == 'String' ? '"' + item.value + '"': item.value}}
+              {{item.dataType == 'String' ? ((item.value == 'null' || item.value == 'undefined') ? item.value : '"' + item.value + '"') : item.value}}
             </span>
         </div>
       </div>

+ 21 - 27
magic-editor/src/console/src/components/editor/magic-script-editor.vue

@@ -494,6 +494,7 @@ export default {
           requestConfig.headers['Content-Type'] = 'application/json'
           requestConfig.transformRequest = []
         } catch (e) {
+          console.log('magic-script-editor', e);
           this.$magicAlert({
             content: 'RequestBody 参数有误,请检查!'
           })
@@ -531,44 +532,37 @@ export default {
     },
     buildRequestBodyData(o) {
       let requestBody = o
-      let newBody = '';
+      let newBody = {}
       if ('Object' == requestBody.dataType) {
-        newBody += '{';
-        newBody += this.createJsonStr(requestBody.children)
-        newBody += '}';
+        let body = {}
+        newBody = this.createJsonData(body, requestBody.children)
       } else if ('Array' == requestBody.dataType) {
-        newBody += '[';
-        newBody += this.createJsonStr(requestBody.children, true)
-        newBody += ']';
+        let body = []
+        newBody = this.createJsonData(body, requestBody.children, true)
       }
-      return JSON.parse(newBody)
+      // console.log('buildRequestBodyData', newBody);
+      return newBody
     },
-    createJsonStr(data, arrayFlag = false) {
-      let body = '';
-      data.map((item, index) => {
-        if (index > 0) {
-          body += ','
-        }
+    createJsonData(newBody, data, arrayFlag = false) {
+      data.map(item => {
+        let key, value = item.value;
         if (!arrayFlag) {
-          body += `"${item.name}": `;
+          key = item.name
         }
         if ('Object' == item.dataType) {
-          body += '{';
-          body += this.createJsonStr(item.children)
-          body += '}';
+          value = {}
+          newBody[key] = this.createJsonData(value, item.children)
         } else if ('Array' == item.dataType) {
-          body += '[';
-          body += this.createJsonStr(item.children, true)
-          body += ']';
+          value = []
+          newBody[key] = this.createJsonData(value, item.children, true)
         } else {
-          if ('String' == item.dataType) {
-            body += `"${item.value}"`;
-          } else {
-            body += `${item.value}`;
-          }
+            newBody[key] = (value == 'null' || value == 'undefined') ? null : value
+        }
+        if (arrayFlag) {
+          newBody.push(value)
         }
       })
-      return body;
+      return newBody;
     },
     viewHistory() {
       if (!this.selected) {

+ 36 - 33
magic-editor/src/console/src/components/layout/magic-request.vue

@@ -254,8 +254,10 @@
     watch: {
       requestBody: {
         handler(newVal, oldVal) {
+          console.log('watch -handler', newVal);
           if (this.bodyEditorFlag) {
             this.info.requestBody = JSON.stringify(newVal[0])
+            // this.buildEditorValue(this.info.requestBody)
           }
         },
         deep: true
@@ -264,7 +266,7 @@
     mounted() {
       let that = this;
       bus.$on('update-request-body', (newVal) => {
-        console.log('update-request-body', newVal);
+        // console.log('update-request-body', newVal);
         this.initRequestBodyDom()
         if (!newVal || newVal == null) {
           that.bodyEditorFlag = false
@@ -274,8 +276,17 @@
         }
         try {
           let body = JSON.parse(newVal)
-          that.requestBody = [body]
-          that.buildEditorValue(body)
+          if (body.dataType && body.children) {
+            that.requestBody = [body]
+            that.buildBodyEditorData(body)
+          } else {
+            /**
+             * 旧的json结构,不能直接用,需通过editor转换
+             */
+            this.editorJson = formatJson(newVal)
+            this.bodyEditor && this.bodyEditor.setValue(this.editorJson)
+          }
+
         } catch (e) {
           // console.log(e);
         }
@@ -285,48 +296,40 @@
     },
 
     methods: {
-      buildEditorValue(o) {
+      buildBodyEditorData(o) {
         let requestBody = o
-        let newBody = '';
+        let newBody = {}
         if ('Object' == requestBody.dataType) {
-          newBody += '{\r\n';
-          newBody += this.createJsonStr(requestBody.children) || '\t'
-          newBody += '\r\n}';
+          let body = {}
+          newBody = this.createJsonData(body, requestBody.children)
         } else if ('Array' == requestBody.dataType) {
-          newBody += '[\r\n';
-          newBody += this.createJsonStr(requestBody.children, true)
-          newBody += '\r\n]';
+          let body = []
+          newBody = this.createJsonData(body, requestBody.children, true)
         }
-        this.editorJson = formatJson(newBody)
-        this.bodyEditor && this.bodyEditor.setValue(formatJson(newBody))
+        // console.log('buildBodyEditorData', newBody);
+        this.editorJson = formatJson(JSON.stringify(newBody))
+        this.bodyEditor && this.bodyEditor.setValue(this.editorJson)
       },
-      createJsonStr(data, arrayFlag = false) {
-        let body = '';
-        data.map((item, index) => {
-          if (index > 0) {
-            body += ','
-          }
+      createJsonData(newBody, data, arrayFlag = false) {
+        data.map(item => {
+          let key, value = item.value;
           if (!arrayFlag) {
-            body += `"${item.name}": `;
+            key = item.name
           }
-
           if ('Object' == item.dataType) {
-            body += '{\r\n';
-            body += this.createJsonStr(item.children)
-            body += '\r\n}';
+            value = {}
+            newBody[key] = this.createJsonData(value, item.children)
           } else if ('Array' == item.dataType) {
-            body += '[\r\n';
-            body += this.createJsonStr(item.children, true)
-            body += '\r\n]';
+            value = []
+            newBody[key] = this.createJsonData(value, item.children, true)
           } else {
-            if ('String' == item.dataType) {
-              body += `"${item.value}"`;
-            } else {
-              body += `${item.value}`;
-            }
+            newBody[key] = (value == 'null' || value == 'undefined') ? null : value
+          }
+          if (arrayFlag) {
+            newBody.push(value)
           }
         })
-        return body;
+        return newBody;
       },
       layout() {
         this.$nextTick(() => {