npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@tuoyuan/api-config-component

v1.1.2

Published

网关接口配置组件 - 可视化配置API接口数据映射

Readme

API Config Component

网关接口配置组件 - 可视化配置 API 接口数据映射

简介

API Config Component 是一个基于 Vue 3 的可视化配置组件,用于配置网关 API 接口的数据映射规则。

核心功能

  1. 选择 API 接口 - 从树形结构中选择目标接口
  2. 配置入参映射 - 支持固定值、模板字符串、函数三种模式
  3. 配置输出结构 - 定义字段提取路径和格式化规则
  4. 输出标准配置 - 生成可存储、可解析的 JSON 配置

应用场景

  • 网关接口数据适配
  • 多数据源统一输出格式
  • 动态表单/表格数据源配置
  • 低代码平台数据源配置

特性

  • 🎯 可视化配置 - 通过界面操作完成复杂的数据映射
  • 🌲 树形 API 选择 - 支持多层级分类和搜索
  • 🔍 智能过滤 - 支持 include/exclude 模式过滤 API
  • 🎨 灵活的入参配置 - 固定值/模板字符串/函数三种模式
  • 📋 Schema 驱动 - 基于 JSON Schema 定义输出结构
  • 🎛️ 字段格式化 - 支持日期、数字、货币等格式化
  • 💾 标准输出 - 输出标准 JSON 配置
  • 🔄 自动推断 - Schema 不完整时自动返回完整数据

安装

npm install api-config-component

yarn add api-config-component

pnpm add api-config-component

快速开始

最简单的使用方式

<template>
  <ApiConfig
    :api-loader="loadApiList"
    @save="handleSave"
  />
</template>

<script setup>
import { ApiConfig } from 'api-config-component';
import 'api-config-component/dist/style.css';

// 加载 API 列表
const loadApiList = async () => {
  const response = await fetch('/api/gateway/list');
  return response.json();
};

// 保存配置
const handleSave = (config) => {
  console.log('保存的配置:', config);
  // 将配置保存到后端
};
</script>

使用工具函数测试配置

<template>
  <ApiConfig
    :api-loader="loadApiList"
    @save="handleSave"
  />
</template>

<script setup>
import { ApiConfig, extractDataBySchema, executeReqMapping } from 'api-config-component';
import 'api-config-component/dist/style.css';

const loadApiList = async () => {
  // 加载 API 列表
};

const handleSave = async (config) => {
  // 1. 执行入参映射
  const params = executeReqMapping(config.reqMapping, {
    pageNum: 1,
    pageSize: 100
  });
  
  // 2. 调用 API
  const response = await fetch(config.apiPath, {
    method: 'POST',
    body: JSON.stringify(params)
  });
  const data = await response.json();
  
  // 3. 提取数据
  const result = extractDataBySchema(data, config.res_schema);
  
  console.log('提取后的数据:', result);
};
</script>

API 文档

Props

| 参数 | 类型 | 必填 | 默认值 | 说明 | |------|------|------|--------|------| | apiLoader | Function | 是* | null | 自定义 API 列表加载函数 | | apiListUrl | String | 是* | '' | 网关 API 列表接口地址 | | resSchema | Object | 否 | null | 输出数据结构模板(JSON Schema) | | includePattern | Array | 否 | [] | 只显示匹配规则的 API,支持通配符 * | | excludePattern | Array | 否 | [] | 排除匹配规则的 API | | initialConfig | Object | 否 | null | 初始配置(编辑模式) |

注意apiLoaderapiListUrl 至少需要提供一个。

Events

| 事件名 | 参数 | 说明 | |--------|------|------| | save | config: Object | 保存配置时触发,返回完整配置对象 | | change | { api, config, resSchema } | 配置变化时触发 |

导出的工具函数

import { 
  ApiConfig,              // 组件
  extractDataBySchema,    // 根据 schema 提取数据
  executeReqMapping,      // 执行入参映射
  extractOutputFields,    // 提取输出字段信息
  formatConfig           // 格式化配置显示
} from 'api-config-component';

extractDataBySchema(data, schema)

根据 res_schema 从原始数据中提取字段。

参数:

  • data - 原始数据对象
  • schema - res_schema 配置

返回: 提取后的数据

示例:

const data = {
  code: 10000,
  msg: '成功',
  data: {
    list: [
      { id: 1, name: '张三' },
      { id: 2, name: '李四' }
    ]
  }
};

const schema = {
  type: 'object',
  x_path: '@.data.list',
  items: {
    type: 'object',
    properties: {
      id: { type: 'integer', x_path: '@.id' },
      name: { type: 'string', x_path: '@.name' }
    }
  }
};

const result = extractDataBySchema(data, schema);
// 结果:[{ id: 1, name: '张三' }, { id: 2, name: '李四' }]

executeReqMapping(reqMapping, context)

执行入参映射,将模板变量替换为实际值。

参数:

  • reqMapping - 入参映射配置
  • context - 上下文数据对象

返回: 执行后的参数对象

示例:

const reqMapping = {
  page_no: '${pageNum}',
  page_size: '${pageSize}',
  keyword: '${searchText}'
};

const context = {
  pageNum: 1,
  pageSize: 100,
  searchText: 'test'
};

const params = executeReqMapping(reqMapping, context);
// 结果:{ page_no: 1, page_size: 100, keyword: 'test' }

使用示例

示例 1:列表接口配置

<template>
  <ApiConfig
    :api-loader="loadApiList"
    :include-pattern="['*.get_list', '*.query*']"
    :exclude-pattern="['*.add', '*.remove', '*.delete']"
    @save="handleSave"
  />
</template>

<script setup>
import { ApiConfig } from 'api-config-component';
import 'api-config-component/dist/style.css';

const loadApiList = async () => {
  const response = await fetch('/api/gateway/list');
  return response.json();
};

const handleSave = (config) => {
  console.log('保存的配置:', config);
  // 保存到后端
  fetch('/api/config/save', {
    method: 'POST',
    body: JSON.stringify(config)
  });
};
</script>

示例 2:树形结构配置

<template>
  <ApiConfig
    :api-loader="loadApiList"
    :include-pattern="['*.get_tree', '*.get_list']"
    @save="handleSave"
  />
</template>

<script setup>
import { ApiConfig } from 'api-config-component';
import 'api-config-component/dist/style.css';

const loadApiList = async () => {
  // 加载 API 列表
};

const handleSave = (config) => {
  console.log('保存配置', config);
};
</script>

示例 3:编辑已有配置

<template>
  <ApiConfig
    :api-loader="loadApiList"
    :initial-config="existingConfig"
    @save="handleSave"
  />
</template>

<script setup>
import { ref } from 'vue';
import { ApiConfig } from 'api-config-component';
import 'api-config-component/dist/style.css';

const existingConfig = ref({
  apiPath: '/api/news/list',
  reqMapping: {
    page_no: '${pageNum}',
    page_size: '${pageSize}'
  },
  res_schema: {
    type: 'object',
    x_path: '@.data.list',
    items: {
      type: 'object',
      properties: {
        id: { type: 'integer', x_path: '@.id' },
        title: { type: 'string', x_path: '@.title' }
      }
    }
  }
});

const loadApiList = async () => {
  // 加载 API 列表
};

const handleSave = (config) => {
  console.log('更新配置', config);
};
</script>

配置输出格式

组件保存后输出标准 JSON 配置:

{
  "apiPath": "/api/news/list",
  "reqMapping": {
    "page_no": "${pageNum}",
    "page_size": "${pageSize}",
    "keyword": "${searchText}"
  },
  "res_schema": {
    "type": "object",
    "x_path": "@.data.list",
    "items": {
      "type": "object",
      "properties": {
        "id": {
          "type": "integer",
          "x_path": "@.id",
          "format": ""
        },
        "title": {
          "type": "string",
          "x_path": "@.title",
          "format": ""
        },
        "publishTime": {
          "type": "string",
          "x_path": "@.publish_time",
          "format": "YYYY-MM-DD HH:mm:ss"
        }
      }
    }
  }
}

入参配置模式

1. 固定值模式

直接使用固定值:

{
  "page_no": 1,
  "page_size": 100,
  "need_total": true
}

2. 模板字符串模式

使用 ${变量名} 引用上下文变量:

{
  "page_no": "${pageNum}",
  "page_size": "${pageSize}",
  "keyword": "${searchText}"
}

不带引号的写法(推荐,自动保持类型):

{
  "page_no": ${pageNum},
  "page_size": ${pageSize}
}

3. 函数模式

使用箭头函数进行复杂计算:

{
  "page_no": "(ctx) => Number(ctx.pageNum) || 1",
  "page_size": "(ctx) => Math.min(ctx.pageSize, 100)",
  "keyword": "(ctx) => ctx.searchText?.trim() || ''"
}

字段格式化

支持多种格式化类型:

日期格式

  • YYYY-MM-DD - 2024-01-01
  • YYYY-MM-DD HH:mm:ss - 2024-01-01 12:00:00
  • YYYY/MM/DD - 2024/01/01
  • timestamp - 时间戳(毫秒)
  • timestamp_s - 时间戳(秒)

数字格式

  • number - 数字
  • integer - 整数
  • currency - 货币(¥1,234.56)
  • percent - 百分比(12.34%)

通用格式

  • string - 字符串
  • boolean - 布尔值
  • json - JSON 字符串

Schema 自动推断

当 API 的 res_schema 不完整(properties 为空)时,组件会自动推断并返回完整的原始数据。

示例:

如果 API 的 schema 是:

{
  "type": "object",
  "properties": {
    "data": {
      "type": "object",
      "properties": {}
    }
  }
}

组件会自动:

  1. 检测到 data.properties 为空
  2. 推测数据路径为 @.data.list
  3. 直接返回 data.list 的完整数据

API 树数据格式

API 列表应返回以下格式:

[
  {
    id: '1',                    // 节点 ID
    name: '系统管理',            // 节点名称
    isLeaf: false,              // 是否叶子节点
    expanded: false,            // 是否展开
    children: [                 // 子节点
      {
        id: '1-1',
        name: '获取用户列表',
        apiPath: '/api/system/user/get_list',  // API 路径
        isLeaf: true,
        _raw: {                 // 原始数据(包含 req_schema、res_schema)
          req_schema: { /* ... */ },
          res_schema: { /* ... */ }
        }
      }
    ]
  }
]

或者使用 funcs 数组(会自动转换为 children):

[
  {
    id: '1',
    name: '系统管理',
    funcs: [                    // 接口列表
      {
        id: '1-1',
        name: '获取用户列表',
        tag: 'system.user.get_list',
        req_schema: { /* ... */ },
        res_schema: { /* ... */ }
      }
    ]
  }
]

过滤规则

includePattern

只显示匹配的 API:

<ApiConfig
  :include-pattern="['*.get_list', '*.query*', 'system.*']"
/>

excludePattern

排除匹配的 API:

<ApiConfig
  :exclude-pattern="['*.add', '*.remove', '*.delete', '*.update']"
/>

通配符规则

  • * - 匹配任意字符
  • *.get_list - 匹配所有以 .get_list 结尾的 API
  • system.* - 匹配所有以 system. 开头的 API
  • *user* - 匹配包含 user 的 API

开发

# 安装依赖
npm install

# 启动开发服务器
npm run dev

# 构建库
npm run build

# 预览
npm run preview

浏览器支持

  • Chrome >= 87
  • Firefox >= 78
  • Safari >= 14
  • Edge >= 88

常见问题

1. 如何处理 Schema 不完整的 API?

组件会自动检测并使用自动推断模式,直接返回完整的原始数据。

2. 模板变量的类型如何保持?

使用不带引号的写法:{"page_no": ${pageNum}},会自动保持原始类型。

3. 如何自定义 API 加载逻辑?

使用 apiLoader prop 提供自定义加载函数:

const loadApiList = async () => {
  const response = await fetch('/your-api');
  return response.json();
};

4. 如何测试配置是否正确?

使用导出的工具函数:

import { extractDataBySchema, executeReqMapping } from 'api-config-component';

// 执行入参映射
const params = executeReqMapping(config.reqMapping, context);

// 调用 API 获取数据
const data = await callApi(config.apiPath, params);

// 提取数据
const result = extractDataBySchema(data, config.res_schema);

License

MIT

贡献

欢迎提交 Issue 和 Pull Request!