生成api js 代码
当前为
// ==UserScript==
// @name SwaggerUI tool
// @namespace http://tampermonkey.net/
// @version 0.1
// @description 生成api js 代码
// @author CGod
// @match https://www.tampermonkey.net/scripts.php
// @require https://cdn.bootcdn.net/ajax/libs/jquery-toast-plugin/1.3.2/jquery.toast.min.js
// @resource toast_css https://cdn.bootcdn.net/ajax/libs/jquery-toast-plugin/1.3.2/jquery.toast.min.css
// @grant GM_addStyle
// @grant GM_setClipboard
// @grant GM_getResourceText
// ==/UserScript==
(function () {
"use strict";
const timer = setInterval(() => {
if (document.getElementById("resources")) {
init();
clearInterval(timer);
}
});
function init() {
$(".operation").each((i, operation) => {
let $operation = $(operation);
let $method = $operation.find(".http_method");
let $copy = $(`<span class="copy_api_code">复制API代码<span>`);
$copy.on("click", () => {
copyApiCode(operation);
});
$method.before($copy);
});
}
function copyApiCode(operation) {
let $operation = $(operation);
let url = $operation.find(".path a").text();
let method = $operation.find(".http_method a").text();
let paramTypes = $operation
.find(".operation-params tr td:nth-child(4)")
.map((i, t) => $(t).text())
.toArray();
let hasData = paramTypes.indexOf("formData") !== -1 || paramTypes.indexOf("body") !== -1;
let hasParams = paramTypes.indexOf("query") !== -1;
let reqOpts = [];
let fnOpts = [];
let apiName = `api${up(method)}`;
url = url.replace(/\{\w+\}/g, s => {
fnOpts.push(s.substring(1, s.length - 1));
return "$" + s;
});
if (method.toLowerCase() !== "get") {
reqOpts.push(`method: '${method}'`);
}
if (hasData) {
fnOpts.push("data");
reqOpts.push("data");
}
if (hasParams) {
fnOpts.push("params");
reqOpts.push("params");
}
let reqOptsStr = reqOpts.length
? `, {
${reqOpts.join(",\n ")}
}`
: "";
let api = `export function ${apiName}(${fnOpts.join(", ")}) {
return request(\`/api-${url}\`${reqOptsStr});
}`;
console.log(api);
GM_setClipboard(api, "text");
$.toast({
text: "代码已复制到剪切板",
loader: false
});
}
function up(s) {
return s.charAt(0).toUpperCase() + s.substr(1);
}
GM_addStyle(GM_getResourceText("toast_css"));
GM_addStyle(`
.copy_api_code {
position: absolute;
left: -103px;
line-height: 28px;
height: 28px;
background: #fff;
display: block;
width: 100px;
text-align: center;
border: 1px dashed #999;
box-sizing: border-box;
cursor: pointer;
transition: all 0.3s;
}
.copy_api_code:hover {
background-color: #eee;
}
.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation {
overflow: inherit;
position: relative;
}
`);
})();