自学内容网 自学内容网

油猴脚本抓取swagger参数,自动生成请求参数

前端开发 ,从 swagger中获取api 以及 参数复制黏贴很麻烦  ;写一个脚本直接生成复制需要的形式

脚本代码:

// ==UserScript==
// @name         swagger.io
// @namespace    http://tampermonkey.net/
// @version      2024-09-18
// @description  try to take over the world!
// @author       You
// @match        https://editor.swagger.io/
// @icon         https://www.google.com/s2/favicons?sz=64&domain=goodcms.vip
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    function addCopyButtons(innerHTMLArray = [] ,descArray=[],requestMethods=[]) {
        // 检查是否有需要复制的内容
        if (innerHTMLArray.length === 0) {
            console.error('No content to copy.');
            return;
        }

        // 创建复制方法按钮容器
        const buttonContainer = document.createElement('div');
        buttonContainer.id = 'copyButtonContainer';
        buttonContainer.style.position = 'fixed';
        buttonContainer.style.top = '100px';
        buttonContainer.style.right = '10px';
        buttonContainer.style.backgroundColor = 'white';
        buttonContainer.style.padding = '10px';
        buttonContainer.style.border = '1px solid #ccc';
        buttonContainer.style.zIndex = '9999';


        // 创建一个复制所有内容的按钮
        const copyAllButton = document.createElement('button');
        copyAllButton.textContent = 'Copy All Cells';
        copyAllButton.onclick = () => {
            console.log("innerHTMLArray",innerHTMLArray)
            //const allText = innerHTMLArray.join('\n'); // 数组每项之间换行
            let allText = ''
            innerHTMLArray.map((item,index)=>{
              let methodStr = `
  /** ${descArray[index]} */
  static ${combineLastTwoElements(item.split("/"))}(data: ${combineLastTwoElements(item.split("/"))}Data) {
    return request<any, any>({
      url: "${item}",
      method: "${requestMethods[index]}",
      data,
      headers: {
        "Content-Type": "application/json",
      },
    });
  }
`
allText+=methodStr
              return  methodStr

            });
            navigator.clipboard.writeText(allText).then(() => {
                console.log('Copied all cells:', allText);
            }, (err) => {
                console.error('Failed to copy all text: ', err);
            });
        };
        buttonContainer.appendChild(copyAllButton);

        document.body.appendChild(buttonContainer);
        console.log("Buttons added to container");
    }
    // 处理 ['', 'admin', 'v1', 'order', 'getRechargeOrderList'];  orderGetRechargeOrderList
    function combineLastTwoElements(arr) {
        // 获取数组的倒数第二个和最后一个元素
        const secondLast = arr[arr.length - 2];
        const last = arr[arr.length - 1];

        // 将最后一个元素的首字母转为大写
        const capitalizedLast = last.charAt(0).toUpperCase() + last.slice(1);

        // 拼接两个元素并返回结果
        return `${secondLast}${capitalizedLast}`;
    }

    function initialize() {

        // 初始化  url 列表
        let urlArray = Array.from(document.querySelectorAll(".nostyle span")).map(element => element.innerHTML).map(url => url.replace(/<wbr>/g, ''));
        urlArray.shift() // 删除第一个不需要

        // 描述列表
        let descArray = Array.from(document.querySelectorAll(".opblock-summary-description")).map(element => element.innerHTML);

        // 请求方法列表
        let requestMethods = Array.from(document.querySelectorAll(".opblock-summary-method")).map(element => element.innerHTML);

        console.log("descArray",descArray)

        // 检查是否有选中的内容
        if (descArray.length > 0) {
            addCopyButtons(urlArray ,descArray,requestMethods);
        } else {
            console.warn('No cells found to copy.');
        }
    }

    // 检查 DOMContentLoaded 事件
    if (document.readyState === 'complete' || (document.readyState !== 'loading' && !document.documentElement.doScroll)) {
        setTimeout(()=>{
          initialize();
        },1000)
    } else {
        document.addEventListener('DOMContentLoaded', initialize);
    }

    // 处理动态加载的情况
    const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            if (document.querySelectorAll("thead div.cell").length > 0) {
                initialize();
                observer.disconnect();  // 只需执行一次
            }
        });
    });

    observer.observe(document.body, { childList: true, subtree: true });
})();

抓取输出示例 :

 /** deleteUserChannel 删除用户渠道 */
  static settingsDeleteUserChannel(data: settingsDeleteUserChannelData) {
    return request<any, any>({
      url: "/admin/v1/settings/deleteUserChannel",
      method: "POST",
      data,
      headers: {
        "Content-Type": "application/json",
      },
    });
  }

  /** deleteWithdrawMethod 删除提现方式 */
  static settingsDeleteWithdrawMethod(data: settingsDeleteWithdrawMethodData) {
    return request<any, any>({
      url: "/admin/v1/settings/deleteWithdrawMethod",
      method: "POST",
      data,
      headers: {
        "Content-Type": "application/json",
      },
    });
  }


原文地址:https://blog.csdn.net/qq_30071431/article/details/142351503

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!