All Downloads are FREE. Search and download functionalities are using the official Maven repository.

META-INF.resources.webjars.battcn.DApiUI.js Maven / Gradle / Ivy

There is a newer version: 1.4.4-RELEASE
Show newest version
(function ($) {
    //初始化类
    var DApiUI = {};
    DApiUI.init = function () {
        $.ajax({
            url: "swagger-resources",
            dataType: "json",
            type: "get",
            async: false,
            success: function (data) {
                console.info(data);
                for (var i = 0; i < data.length; i++) {
                    var menu = data[i];
                    var url = menu.location;
                    console.info(url);
                    $.ajax({
                        url: menu.location,
                        dataType: "json",
                        type: "get",
                        async: false,
                        success: function (data) {
                            var menu = data;
                            console.info(menu);
                            DApiUI.definitions(menu);
                            DApiUI.createDescription(menu);
                            DApiUI.initTreeMenu(menu);
                            DApiUI.eachPath(menu);
                        }
                    })
                }
            }
        });
    };

    /***
     * 创建面板
     */
    DApiUI.creatabTab = function () {
        var divcontent = $('
'); var ul = $(''); ul.append($('
  • ')); ul.append($('
  • 在线调试
  • ')); divcontent.append(ul); var tabcontent = $('
    '); tabcontent.append($('
    接口详细说明

    Bootstrap 使用到的某些 HTML 元素和 CSS 属性需要将页面设置为 HTML5 文档类型。在你项目中的每个页面都要参照下面的格式进行设置。

    ')); tabcontent.append($('
    正在开发中,敬请期待......
    ')); divcontent.append(tabcontent); //内容覆盖 DApiUI.getDoc().html(""); DApiUI.getDoc().append(divcontent); DApiUI.log("动态激活..."); DApiUI.getDoc().find("#myTab a:first").tab('show') }; /*** * 检查对象属性,in并赋予默认值 * @param obj * @param key * @param defaultValue * @param checkEmpty * @returns {*} */ DApiUI.getValue = function (obj, key, defaultValue, checkEmpty) { var val = defaultValue; if (obj !== null && obj !== undefined) { if (obj.hasOwnProperty(key)) { val = obj[key]; if (checkEmpty) { if (val === null || val === "") { val = defaultValue; } } } } return val; }; /*** * 创建简介table页面 * @param menu */ DApiUI.createDescription = function (menu) { var table = $('
    '); var title = "", description = "", name = "", version = "", termsOfService = ""; var host = DApiUI.getValue(menu, "host", "", true); if (menu.hasOwnProperty("info")) { var info = menu.info; title = DApiUI.getValue(info, "title", "Swagger-Bootstrap-UI-接口文档", true); description = DApiUI.getValue(info, "description", "", true); if (info.hasOwnProperty("contact")) { var contact = info["contact"]; name = DApiUI.getValue(contact, "name", "", true); } version = DApiUI.getValue(info, "version", "", true); termsOfService = DApiUI.getValue(info, "termsOfService", "", true); } //修改title $("title").html("").html(title); table.append($('' + title + '')); var tbody = $(''); tbody.append($('简介' + description + '')); tbody.append($('作者' + name + '')); tbody.append($('版本' + version + '')); tbody.append($('host' + host + '')); tbody.append($('服务url' + termsOfService + '')); table.append(tbody); var div = $('
    '); div.append(table); //内容覆盖 DApiUI.getDoc().html(""); DApiUI.getDoc().append(div); DApiUI.getDoc().data("data", menu); }; /*** * 获取菜单结构 */ DApiUI.getMenuConstructs = function () { return DApiUI.getDoc().data("data"); }; DApiUI.toString = function (obj, defaultStr) { if (obj !== null && typeof (obj) !== "undefined") { return obj.toString(); } if (obj === undefined) { return defaultStr; } return defaultStr; }; /*** * 初始化菜单树 * @param menu */ DApiUI.initTreeMenu = function (menu) { //遍历tags var tags = []; //简介li var dli = $('
  • 简介
  • '); dli.on("click", function () { DApiUI.log("简介click"); DApiUI.createDescription(menu); dli.addClass("active"); }); DApiUI.getMenu().html(""); DApiUI.getMenu().append(dli); var methodApis = DApiUI.eachPath(menu); $.each(menu.tags, function (i, tag) { var tagInfo = new TagInfo(tag.name, tag.description); //查找childrens $.each(methodApis, function (i, methodApi) { //判断tags是否相同 if (methodApi.tag === tagInfo.name) { tagInfo.childrens.push(methodApi); } }); var len = tagInfo.childrens.length; if (len === 0) { var li = $('
  • ' + tagInfo.name + '
  • '); DApiUI.getMenu().append(li); } else { //存在子标签 var li = $('
  • '); var titleA = $('' + tagInfo.name + "   " + tagInfo.description + '' + len + ''); li.append(titleA); //循环树 var ul = $(''); $.each(tagInfo.childrens, function (i, children) { var childrenLi = $(''); childrenLi.data("data", children); ul.append(childrenLi); }); li.append(ul); DApiUI.getMenu().append(li); } }); DApiUI.log("菜单初始化完成..."); DApiUI.initLiClick(); }; DApiUI.eachPath = function (menu) { var paths = menu.paths; DApiUI.log(paths); //paths是object对象,key是api接口地址, var methodApis = []; for (var key in paths) { var obj = paths[key]; //遍历obj,获取api接口访问方式 //八中方式类型,直接判断 if (obj.hasOwnProperty("get")) { //get方式 var apiInfo = new ApiInfo(obj["get"]); apiInfo.methodType = "get"; apiInfo.url = key; methodApis.push(apiInfo); } if (obj.hasOwnProperty("post")) { //post 方式 var apiInfo = new ApiInfo(obj["post"]); apiInfo.methodType = "post"; apiInfo.url = key; methodApis.push(apiInfo); } if (obj.hasOwnProperty("put")) { //put var apiInfo = new ApiInfo(obj["put"]); apiInfo.methodType = "put"; apiInfo.url = key; methodApis.push(apiInfo); } if (obj.hasOwnProperty("delete")) { //delete var apiInfo = new ApiInfo(obj["delete"]); apiInfo.methodType = "delete"; apiInfo.url = key; methodApis.push(apiInfo); } } //console.log(methodApis); return methodApis; }; /*** * li标签click事件 */ DApiUI.initLiClick = function () { DApiUI.getMenu().find(".menuLi").bind("click", function (e) { e.preventDefault(); var that = $(this); var data = that.data("data"); DApiUI.log("Li标签click事件"); DApiUI.log(data); //获取parent-Li的class属性值 var parentLi = that.parent().parent(); DApiUI.log(parentLi); var className = parentLi.prop("class"); DApiUI.log(className); DApiUI.getMenu().find("li").removeClass("active"); //parentLi.addClass("active"); that.addClass("active"); DApiUI.createApiInfoTable(data); DApiUI.createDebugTab(data); }) }; DApiUI.getStringValue = function (obj) { var str = ""; if (typeof (obj) !== 'undefined' && obj !== null) { str = obj.toString(); } return str; }; /*** * 格式化json * @param text_value */ function formatterJson(text_value) { var res = ""; for (var i = 0, j = 0, k = 0, ii, ele; i < text_value.length; i++) {//k:缩进,j:""个数 ele = text_value.charAt(i); if (j % 2 === 0 && ele === "}") { k--; for (ii = 0; ii < k; ii++) ele = " " + ele; ele = "\n" + ele; } else if (j % 2 === 0 && ele === "{") { ele += "\n"; k++; //debugger; for (ii = 0; ii < k; ii++) ele += " "; } else if (j % 2 === 0 && ele === ",") { ele += "\n"; for (ii = 0; ii < k; ii++) ele += " "; } else if (ele === "\"") j++; res += ele; } return res; } /** * 创建调试面板 */ DApiUI.createDebugTab = function (apiInfo) { DApiUI.log("创建调试tab"); //方法、请求类型、发送按钮 var div = $('
    '); var headdiv1 = $('
    ' + '' + DApiUI.getStringValue(apiInfo.methodType) + '' + '' + '
    '); /* input-group m-bot15 input-group-btn * form-control * * */ div.append(headdiv1); //请求参数 var divp = $('
    请求参数
    '); var divpbody = $('
    '); //是否是文件上传 var fileform = false; //判断是否有请求参数 if (typeof (apiInfo.parameters) !== 'undefined' && apiInfo.parameters !== null) { var table = $('
    '); var thead = $('参数名称参数值操作'); table.append(thead); var tbody = $(''); $.each(apiInfo.parameters, function (i, param) { var tr = $(''); tr.data("data", param); //判断parame的in类型 //query--text //body--textarea var checkbox = $('
    '); var key = $(''); //var value=$(''); var value = $(''); var val = null; if (param["in"] === "body") { tbody.attr("reqtype", "body"); val = $(''); //判断是否有schma if (param.hasOwnProperty("schema")) { var schema = param["schema"]; var ref = schema["$ref"]; var regex = new RegExp("#/definitions/(.*)$", "ig"); if (regex.test(ref)) { var refType = RegExp.$1; //这里判断refType是否是MultipartFile类型,如果是该类型,上传组件 if (refType === "MultipartFile") { fileform = true; val = $(''); } else { //find in definitionsArray var definitionsArray = DApiUI.getDoc().data("definitionsArray"); var deftion = null; for (var i = 0; i < definitionsArray.length; i++) { var definition = definitionsArray[i]; if (definition.key === refType) { deftion = definition.value; break; } } //遍历proprietary for (var k in deftion) { deftion[k] = ""; } if (deftion !== null) { //赋值 val.val(formatterJson(JSON.stringify(deftion))); } } } } } else { val = $(''); //判断是否有defaultvalue if (param.hasOwnProperty("default")) { var defaultValue = param["default"]; val.val(defaultValue); } //这里判断param类型,如果是int类型,只能输入数字 } value.append(val); var oper = $(''); //删除事件 oper.find("button").on("click", function (e) { e.preventDefault(); var that = $(this); that.parent().parent().remove(); }); //判断参数类型,针对path参数 if (param["in"] === "path") { //赋予change事件 value.find("input").on("keyup", function () { var t = $(this); var name = t.data("name"); var apiUrl = t.attr("data-apiUrl"); var realValue = apiUrl.replace("{" + name + "}", t.val()); //查找是否还存在其他path参数 $("#paramBody").find("tr").each(function (i, itr) { var itrthat = $(this); var itrdata = itrthat.data("data"); var itrname = itrdata["name"]; if (itrdata["in"] === "path" && itrdata["name"] !== name) { //查找value值 var itrtdvalue = itrthat.find(".p-value").val(); if (itrtdvalue !== "") { realValue = realValue.replace("{" + itrname + "}", itrtdvalue); } } }); DApiUI.log(realValue); $("#txtreqUrl").val(realValue); DApiUI.log("keyup。。。。") }) } tr.append(checkbox).append(key).append(value).append(oper); tbody.append(tr); }); table.append(tbody); //如果有文件上传,追加form表单 if (fileform) { var form = $('
    '); form.append(table); divpbody.append(form); } else { divpbody.append(table); } } else { divpbody.append($('暂无参数')) } divp.append(divpbody); // if (fileform) { //追加iframe var resptabframe = $('
    '); divp.append(resptabframe); } div.append(divp); //创建reesponsebody var respcleanDiv = $('
    '); div.append(respcleanDiv); DApiUI.getDoc().find("#tab2").find(".panel-body").html(""); DApiUI.getDoc().find("#tab2").find(".panel-body").append(div); //发送事件 headdiv1.find("#btnRequest").bind("click", function (e) { e.preventDefault(); respcleanDiv.html(""); DApiUI.log("发送请求"); // var params = {}; var headerparams = {}; var bodyparams = ""; //modify by xiaoyumin 2017-8-9 11:28:16 //增加表单验证 var validateflag = false; var validateobj = {}; //获取参数 var paramBody = DApiUI.getDoc().find("#tab2").find("#paramBody"); DApiUI.log("paramsbody.."); DApiUI.log(paramBody); //组装请求url var url = DApiUI.getStringValue(apiInfo.url); var cacheData = DApiUI.getDoc().data("data"); if (typeof (cacheData.basePath) !== "undefined" && cacheData.basePath !== "") { if (cacheData.basePath !== "/") { DApiUI.log("NOT ROOT PATH:"); url = cacheData.basePath + DApiUI.getStringValue(apiInfo.url); } } paramBody.find("tr").each(function () { var paramtr = $(this); var cked = paramtr.find("td:first").find(":checked").prop("checked"); DApiUI.log(cked); if (cked) { //如果选中 var trdata = paramtr.data("data"); DApiUI.log("trdata...."); DApiUI.log(trdata); //获取key //var key=paramtr.find("td:eq(1)").find("input").val(); var key = trdata["name"]; //获取value var value = ""; if (trdata["in"] === "body") { value = paramtr.find("td:eq(2)").find("textarea").val(); //这里需要判断schema if (trdata.hasOwnProperty("schema")) { var schema = trdata["schema"]; if (schema.hasOwnProperty("$ref")) { var ref = schema["$ref"]; var regex = new RegExp("#/definitions/(.*)$", "ig"); if (regex.test(ref)) { var refType = RegExp.$1; //这里判断refType是否是MultipartFile类型,如果是该类型,上传组件 if (refType === "MultipartFile") { value = paramtr.find("td:eq(2)").find("input").val(); } } } } } else { value = paramtr.find("td:eq(2)").find("input").val(); } //var value=paramtr.find("td:eq(2)").find("input").val(); //delete方式参数url传递 if (apiInfo.methodType === "delete") { //判断是否是path参数 if (trdata["in"] === "path") { url = url.replace("{" + key + "}", value); } else { if (url.indexOf("?") > -1) { url = url + "&" + key + "=" + value; } else { url += "?" + key + "=" + value; } } } else { if (trdata["in"] === "path") { url = url.replace("{" + key + "}", value); } else { if (trdata["in"] === "body") { bodyparams += value; } else { if (trdata["in"] === "header") { headerparams[key] = value; } else { params[key] = value; } } } } //判断是否required if (trdata.hasOwnProperty("required")) { var required = trdata["required"]; if (required) { //必须,验证value是否为空 if (value === null || value === "") { validateflag = true; var des = trdata["name"]; validateobj = {message: des + "不能为空"}; return false; } } } DApiUI.log("key:" + key + ",value:" + value); } }); DApiUI.log("获取参数.."); DApiUI.log(params); DApiUI.log(apiInfo); DApiUI.log("请求url:" + url); var reqdata = null; //console.log(paramBody.attr("reqtype")) var contType = "application/json; charset=UTF-8"; if (paramBody.attr("reqtype") !== null && paramBody.attr("reqtype") !== undefined && paramBody.attr("reqtype") === "body") { reqdata = bodyparams; } else { reqdata = params; contType = "application/x-www-form-urlencoded; charset=UTF-8"; } //console.log(reqdata) if (validateflag) { layer.msg(validateobj.message); return; } //判断是否有表单 var form = $("#uploadForm"); if (form.length > 0) { form[0].submit(); //console.log("表单提交") //iframe监听change事件 $("#uploadIframe").on("load", function () { //console.log("uploadIframe changed....") $(this).unbind('load'); var framebody = $(this).contents().find("body"); var ret = framebody.html(); //是否存在pre标签 if (framebody.find("pre").length > 0) { ret = framebody.find("pre").html(); } var res; try { res = JSON.parse(ret); //console.log(res) var resptab = $('
    '); var ulresp = $(''); resptab.append(ulresp); var respcontent = $('
    '); var resp1 = $('
    '); respcontent.append(resp1); resptab.append(respcontent); respcleanDiv.append(resptab); var jsondiv = $('
    '); jsondiv.JSONView(res); resp1.find(".panel-body").append(jsondiv); resptab.find("a:first").tab("show"); } catch (err) { //nothing to do,default to show respcleanDiv.html(ret); } }) } else { $.ajax({ url: url, headers: headerparams, type: DApiUI.getStringValue(apiInfo.methodType), data: reqdata, contentType: contType, success: function (data, status, xhr) { var resptab = $('
    '); var ulresp = $(''); resptab.append(ulresp); var respcontent = $('
    '); var resp1 = $('
    '); var resp2 = $('
    暂无
    '); var resp3 = $('
    暂无
    '); respcontent.append(resp1).append(resp2).append(resp3); resptab.append(respcontent); respcleanDiv.append(resptab); DApiUI.log(xhr); DApiUI.log(xhr.getAllResponseHeaders()); var allheaders = xhr.getAllResponseHeaders(); if (allheaders !== null && typeof (allheaders) !== 'undefined' && allheaders !== "") { var headers = allheaders.split("\r\n"); var headertable = $('
    请求头value
    '); for (var i = 0; i < headers.length; i++) { var header = headers[i]; if (header !== null && header !== "") { var headerValu = header.split(":"); var headertr = $('' + headerValu[0] + '' + headerValu[1] + ''); headertable.append(headertr); } } //设置Headers内容 resp3.find(".panel-body").html(""); resp3.find(".panel-body").append(headertable); } var contentType = xhr.getResponseHeader("Content-Type"); DApiUI.log("Content-Type:" + contentType); DApiUI.log(xhr.hasOwnProperty("responseJSON")); if (xhr.hasOwnProperty("responseJSON")) { //如果存在该对象,服务端返回为json格式 resp1.find(".panel-body").html(""); DApiUI.log(xhr["responseJSON"]); var pre = $('
    ');
                                var jsondiv = $('
    '); jsondiv.JSONView(xhr["responseJSON"]); pre.html(JSON.stringify(xhr["responseJSON"], null, 2)); resp1.find(".panel-body").append(jsondiv); } else { //判断content-type //如果是image资源 var regex = new RegExp('image/(jpeg|jpg|png|gif)', 'g'); if (regex.test(contentType)) { var d = DApiUI.getDoc().data("data"); var imgUrl = "http://" + d.host + apiInfo.url; var img = document.createElement("img"); img.onload = function (e) { window.URL.revokeObjectURL(img.src); // 清除释放 }; img.src = imgUrl; resp1.find(".panel-body").html(""); resp1.find(".panel-body")[0].appendChild(img); } else { //判断是否是text var regex = new RegExp('.*?text.*', 'g'); if (regex.test(contentType)) { resp1.find(".panel-body").html(""); resp1.find(".panel-body").html(xhr.responseText); } } } DApiUI.log("tab show..."); resptab.find("a:first").tab("show"); }, error: function (xhr, textStatus, errorThrown) { DApiUI.log("error....."); DApiUI.log(xhr); DApiUI.log(textStatus); DApiUI.log(errorThrown); var resptab = $('
    '); var ulresp = $(''); resptab.append(ulresp); var respcontent = $('
    '); var resp1 = $('
    '); var resp2 = $('
    暂无
    '); var resp3 = $('
    暂无
    '); respcontent.append(resp1).append(resp2).append(resp3); resptab.append(respcontent); respcleanDiv.append(resptab); DApiUI.log(xhr); DApiUI.log(xhr.getAllResponseHeaders()); var allheaders = xhr.getAllResponseHeaders(); if (allheaders !== null && typeof (allheaders) !== 'undefined' && allheaders !== "") { var headers = allheaders.split("\r\n"); var headertable = $('
    请求头value
    '); for (var i = 0; i < headers.length; i++) { var header = headers[i]; if (header !== null && header !== "") { var headerValu = header.split(":"); var headertr = $('' + headerValu[0] + '' + headerValu[1] + ''); headertable.append(headertr); } } //设置Headers内容 resp3.find(".panel-body").html(""); resp3.find(".panel-body").append(headertable); } var contentType = xhr.getResponseHeader("Content-Type"); DApiUI.log("Content-Type:" + contentType); var jsonRegex = ""; DApiUI.log(xhr.hasOwnProperty("responseJSON")); if (xhr.hasOwnProperty("responseJSON")) { //如果存在该对象,服务端返回为json格式 resp1.find(".panel-body").html(""); DApiUI.log(xhr["responseJSON"]); var jsondiv = $('
    '); jsondiv.JSONView(xhr["responseJSON"]); resp1.find(".panel-body").append(jsondiv); } else { //判断是否是text var regex = new RegExp('.*?text.*', 'g'); if (regex.test(contentType)) { resp1.find(".panel-body").html(""); resp1.find(".panel-body").html(xhr.responseText); } } DApiUI.log("tab show..."); resptab.find("a:first").tab("show"); } }) } }) }; DApiUI.createDebugResponseTab = function (parent, data) { }; DApiUI.writeUTF8 = function (str, isGetBytes) { var back = [], byteSize = 0; for (var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push((192 | (31 & (code >> 6)))); back.push((128 | (63 & code))) } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push((224 | (15 & (code >> 12)))); back.push((128 | (63 & (code >> 6)))); back.push((128 | (63 & code))) } } for (i = 0; i < back.length; i++) { if (back[i] > 255) { back[i] &= 255 } } if (isGetBytes) { return back } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }; DApiUI.createApiInfoTable = function (apiInfo) { var table = $('
    '); var thead = $('API接口文档'); table.append(thead); var tbody = $(''); var url = $('接口url' + DApiUI.getStringValue(apiInfo.url) + ''); tbody.append(url); var summary = $('接口名称' + DApiUI.getStringValue(apiInfo.summary) + ''); tbody.append(summary); var description = $('说明' + DApiUI.getStringValue(apiInfo.description) + ''); tbody.append(description); var methodType = $('请求方式' + DApiUI.getStringValue(apiInfo.methodType) + ''); tbody.append(methodType); var consumesArr = DApiUI.getValue(apiInfo, "consumes", [], true); var consumes = $('consumes' + consumesArr + ''); tbody.append(consumes); var producesArr = DApiUI.getValue(apiInfo, "produces", [], true); var produces = $('produces' + producesArr + ''); tbody.append(produces); //请求参数 var args = $('请求参数'); //判断是否有请求参数 if (typeof (apiInfo.parameters) !== 'undefined' && apiInfo.parameters !== null) { var ptd = $(""); var ptable = $('
    '); var table2 = $("
      "); table2.append($("
    • 参数名称" + "说明" + "类型" + "in" + "是否必须
    • ")); ptable.append(table2); $.each(apiInfo.parameters, function (i, param) { //判断是否是ref,如果是,列出他的属性说明 var refflag = false; //判断是否有type属性,如果有,则后端为实体类形参 var ptype = "string"; if (param.hasOwnProperty("type")) { ptype = param["type"]; } else { ///判断是有schma if (param.hasOwnProperty("schema")) { var schema = param["schema"]; //是否有type if (schema.hasOwnProperty("type")) { ptype = schema["type"]; } else if (schema.hasOwnProperty("$ref")) { //是否是ref var regex = new RegExp("#/definitions/(.*)$", "ig"); if (regex.test(schema["$ref"])) { refflag = true; ptype = RegExp.$1; } } } } var ptr = null; //列出属性 if (refflag) { ptr = $('
    • ' + param.name + '' + DApiUI.getStringValue(param['description']) + '' + ptype + '' + DApiUI.getStringValue(param['in']) + '' + param['required'] + '
    • '); ptr.find("span:first-child").attr({ "data-parent": '#accordion', 'data-toggle': 'collapse', 'href': "#" + param.name }).css({"color":"#428BCA","cursor":"pointer"}) .append($("")); table2.append(ptr); var definitionsArray = DApiUI.getDoc().data("definitionsArray"); var mcs = DApiUI.getMenuConstructs(); for (var k in mcs.definitions) { if (ptype === k) { var tp = mcs.definitions[ptype]; var props = tp["properties"]; var $div = $("
        ") for (var prop in props) { var pvalue = props[prop]; var tr = $("
      • "); tr.append($("" + prop + "")); tr.append($("" + DApiUI.toString(pvalue.description, "") + "")); var type = DApiUI.toString(pvalue.type, "string"); tr.append($("" + type + "")); tr.append($("" + DApiUI.getStringValue(param['in']) + "")); tr.append($("" + param['required'] + "")); $div.append(tr); } table2.append($div); } } } else { ptr = $('
      • ' + param.name + '' + DApiUI.getStringValue(param['description']) + '' + ptype + '' + DApiUI.getStringValue(param['in']) + '' + param['required'] + '
      • '); // ptr = $('' + param.name + '' + DApiUI.getStringValue(param['description']) + '' + ptype + '' + DApiUI.getStringValue(param['in']) + '' + param['required'] + ''); table2.append(ptr); } }); table2.append($('
      • 填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充
      • ')); ptable.append(table2); ptd.append(ptable); args.append(ptd); } else { args.append($('暂无')); } tbody.append(args); //响应数据结构 var responseConstruct = $('响应Model'); var responseConstructtd = $(''); responseConstructtd.append(DApiUI.createResponseDefinition(apiInfo)); responseConstruct.append(responseConstructtd); tbody.append(responseConstruct); //响应参数 add by xiaoymin 2017-8-20 16:17:18 var respParams = $('响应参数说明'); var respPart = $(''); respPart.append(DApiUI.createResponseDefinitionDetail(apiInfo)); respParams.append(respPart); tbody.append(respParams); //响应状态码 var response = $('响应'); if (typeof (apiInfo.responses) !== 'undefined' && apiInfo.responses !== null) { var resp = apiInfo.responses; var ptd = $(""); var ptable = $('
        '); var phead = $('状态码说明schema'); ptable.append(phead); var pbody = $(''); if (resp.hasOwnProperty("200")) { var ptr = $('200http响应成功'); pbody.append(ptr); } //400 pbody.append($('400Bad Request 请求出现语法错误,一般是请求参数不对')); //404 pbody.append($('404Not Found 无法找到指定位置的资源')); //401 pbody.append($('401Unauthorized 访问被拒绝')); //403 pbody.append($('403Forbidden 资源不可用')); //500 pbody.append($('500服务器内部错误,请联系Java后台开发人员!!!')); ptable.append(pbody); ptd.append(ptable); response.append(ptd); } else { response.append($("暂无")); } tbody.append(response); table.append(tbody); DApiUI.creatabTab(); //内容覆盖 //查找接口doc //DApiUI.getDoc().find("#tab1").find(".panel-body").html(""); //DApiUI.getDoc().find("#tab1").find(".panel-body").append(table); DApiUI.getDoc().find("#tab1").html(""); DApiUI.getDoc().find("#tab1").append(table); }; /*** * 响应参数详情 * @param apiInfo */ DApiUI.createResponseDefinitionDetail = function (apiInfo) { var resp = apiInfo.responses; var div = $("
        "); if (resp.hasOwnProperty("200")) { var ok = resp["200"]; if (ok.hasOwnProperty("schema")) { var schema = ok["schema"]; var ref = schema["$ref"]; var regex = new RegExp("#/definitions/(.*)$", "ig"); if (regex.test(ref)) { var refType = RegExp.$1; var definitionsArray = DApiUI.getDoc().data("definitionsArray"); var mcs = DApiUI.getMenuConstructs(); for (var k in mcs.definitions) { if (refType === k) { var table = $("
          "); table.append("
        • 参数名称" + "类型" + "说明
        • "); var tp = mcs.definitions[refType]; var props = tp["properties"]; for (var prop in props) { var pvalue = props[prop]; var tr = $("
        • "); //只遍历一级属性 //判断是否是ref if (pvalue.hasOwnProperty("items") || pvalue.hasOwnProperty("$ref")) { var param_ref = (pvalue["items"] && pvalue["items"]["$ref"]) || pvalue["$ref"]; var regex1 = new RegExp("#/definitions/(.*)$", "ig"); if (regex1.test((param_ref))) { var type = DApiUI.toString(pvalue.type, "string"); var ptype = param_ref.slice(param_ref.lastIndexOf("/") + 1); tr.append($("" + prop + "")); tr.append($("" + type + "")); tr.append($("" + pvalue.description + "")); tr.find("span:first-child").attr({ "data-parent": '#accordion', 'data-toggle': 'collapse', 'href': "#" + prop }).css({"color":"#428BCA","cursor":"pointer"}) .append(""); table.append(tr); for (var j in mcs.definitions) { if (ptype === j) { var tpp = mcs.definitions[ptype]; var pp_props = tpp["properties"]; var $div = $("
            ") for (var prop1 in pp_props) { var tr1 = $("
          • "); var pvalue1 = pp_props[prop1]; tr1.append($("" + prop1 + "")); tr1.append($("" + DApiUI.getValue(pvalue1, "type", "string", true) + "")); tr1.append($("" + DApiUI.getValue(pvalue1, "description", "", true) + "")); $div.append(tr1); } table.append($div); } } } } else { tr.append($("" + prop + "")); var type = DApiUI.toString(pvalue.type, "string"); tr.append($("" + type + "")); tr.append($("" + DApiUI.toString(pvalue.description, "") + "")); table.append(tr); } } table.append($('
          • 填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充填充
          • ')); div.append(table) } } } } } return div; }; DApiUI.createResponseDefinition = function (apiInfo) { var resp = apiInfo.responses; var div = $("
            暂无
            "); if (resp.hasOwnProperty("200")) { var ok = resp["200"]; if (ok.hasOwnProperty("schema")) { var schema = ok["schema"]; var ref = schema["$ref"]; var regex = new RegExp("#/definitions/(.*)$", "ig"); if (regex.test(ref)) { var refType = RegExp.$1; //这里去definitionsArrar查找,如果未找到,直接展示refType var flag = false; var htmlValue = refType; var definitionsArray = DApiUI.getDoc().data("definitionsArray"); for (var i = 0; i < definitionsArray.length; i++) { var definition = definitionsArray[i]; if (definition.key === refType) { flag = true; htmlValue = definition.value; break; } } div.html(""); if (flag) { div.JSONView(htmlValue); } else { div.html(refType); } } else { //未发现ref属性 if (schema.hasOwnProperty("type")) { div.html(""); div.html(schema["type"]); } } } } return div; }; DApiUI.definitions = function (menu) { var definitionsArray = []; DApiUI.log("definitionsArray...."); if (menu !== null && typeof (menu) !== "undefined" && menu.hasOwnProperty("definitions")) { var definitions = menu["definitions"]; for (var definition in definitions) { var defiType = new definitionType(); defiType.key = definition; //获取value var value = definitions[definition]; if (checkUndefined(value)) { //是否有properties if (value.hasOwnProperty("properties")) { var properties = value["properties"]; var defiTypeValue = {}; for (var property in properties) { var propobj = properties[property]; //默认string类型 var propValue = ""; //判断是否有类型 if (propobj.hasOwnProperty("type")) { var type = propobj["type"]; //判断是否有example if (propobj.hasOwnProperty("example")) { propValue = propobj["example"]; } else if (checkIsBasicType(type)) { propValue = getBasicTypeValue(type); } else { if (type === "array") { propValue = []; var items = propobj["items"]; var ref = items["$ref"]; var regex = new RegExp("#/definitions/(.*)$", "ig"); if (regex.test(ref)) { var refType = RegExp.$1; //这里需要递归判断是否是本身,如果是,则退出递归查找 if (refType !== definition) { propValue.push(findRefDefinition(refType, definitions)); } } } } } else { if (propobj.hasOwnProperty("$ref")) { var ref = propobj["$ref"]; var regex = new RegExp("#/definitions/(.*)$", "ig"); if (regex.test(ref)) { var refType = RegExp.$1; //这里需要递归判断是否是本身,如果是,则退出递归查找 if (refType !== definition) { propValue = findRefDefinition(refType, definitions); } else { propValue = {}; } } } else { propValue = {}; } } defiTypeValue[property] = propValue; } defiType.value = defiTypeValue; } else { defiType.value = {}; } } definitionsArray.push(defiType); } } DApiUI.getDoc().data("definitionsArray", definitionsArray); }; DApiUI.getDefinitions = function () { return DApiUI.getDoc().data("definitionsArray"); }; function checkIsBasicType(type) { var basicTypes = ["string", "integer", "number", "object", "boolean"]; var flag = false; if ($.inArray(type, basicTypes) > -1) { flag = true; } return flag; } function getBasicTypeValue(type) { var propValue = ""; //是否是基本类型 if (type === "integer") { propValue = 0; } if (type === "boolean") { propValue = true; } if (type === "object") { propValue = {}; } if (type === "number") { propValue = parseFloat(0); } return propValue; } function findRefDefinition(definitionName, definitions) { var defaultValue = ""; for (var definition in definitions) { if (definitionName === definition) { var value = definitions[definition]; //是否有properties if (value.hasOwnProperty("properties")) { var properties = value["properties"]; var defiTypeValue = {}; for (var property in properties) { var propobj = properties[property]; //默认string类型 var propValue = ""; //判断是否有类型 if (propobj.hasOwnProperty("type")) { var type = propobj["type"]; //判断是否有example if (propobj.hasOwnProperty("example")) { propValue = propobj["example"]; } else if (checkIsBasicType(type)) { propValue = getBasicTypeValue(type); } else { if (type === "array") { propValue = []; var items = propobj["items"]; var ref = items["$ref"]; //var regex = new RegExp("#/definitions/(.*)$", "ig"); //if (regex.test(ref)) { var refType = RegExp.$1; if (refType !== definitionName) { propValue.push(findRefDefinition(refType, definitions)); } //} } } } else { } defiTypeValue[property] = propValue; } defaultValue = defiTypeValue; } else { defaultValue = {}; } } } return defaultValue; } function checkUndefined(obj) { var flag = false; if (obj !== null && typeof (obj) !== "undefined") { flag = true; } return flag; } function definitionType() { this.key = ""; this.value = {}; } /*** * 获取默认请求参数类型 * @param obj * @returns {string} */ DApiUI.getDefaultRequiredType = function (obj) { var t = "string"; if (typeof (obj) !== 'undefined' && obj !== null) { t = obj.toString(); } return t; }; /*** * 查找子类 * @param tagInfo * @param menu */ DApiUI.initChildrens = function (tagInfo, menu) { }; DApiUI.getDoc = function () { return $("#content"); }; DApiUI.getMenu = function () { return $("#menu"); }; DApiUI.log = function (msg) { if (window.console) { console.log(msg); } }; DApiUI.init(); /*** * 标签组信息 * @constructor */ function TagInfo(name, description) { this.name = name; this.description = description; this.childrens = []; } /*** * api实体信息 * @param options * @constructor */ function ApiInfo(options) { //判断options this.tag = ""; this.url = ""; this.description = ""; this.operationId = ""; this.parameters = []; this.produces = []; this.responses = {}; this.methodType = "post"; this.consumes = []; this.summary = ""; if (options !== null && typeof (options) !== 'undefined') { this.tag = options.tags[0]; this.description = options.description; this.operationId = options.operationId; this.summary = options.summary; this.parameters = options.parameters; this.produces = options.produces; this.responses = options.responses; this.consumes = options.consumes; } } })(jQuery);




            © 2015 - 2024 Weber Informatics LLC | Privacy Policy