feat(method-doc): API 文档库表化维护脚本(create/update/get/list/delete/import/export)与 wms_api_method_doc 建表迁移

This commit is contained in:
liufumingren 2026-09-24 03:20:23 +08:00
parent dd2f47c59c
commit 24ffb5896e
11 changed files with 882 additions and 0 deletions

View File

@ -0,0 +1,171 @@
'use strict';
/**
* API 方法文档库表化(2026-09-23):
* - wms_api_method_doc:方法文档表(methods/system.json 的维护源)
* - wms_method_doc_meta:文档元信息表(docName 维度单行:描述/全局 headers/version/updatedAt)
*
* methods/system.json 由导出脚本 script/method-doc-export.cjs 生成,docs 页面仍读文件。
*/
const DOC_TABLE = 'wms_api_method_doc';
const META_TABLE = 'wms_method_doc_meta';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable(DOC_TABLE, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
method: {
type: Sequelize.STRING(128),
allowNull: false,
comment: '方法名(如 wechat.userList)',
},
module: {
type: Sequelize.STRING(64),
allowNull: false,
comment: '模块标识(group.module,如 wechat)',
},
group_name: {
type: Sequelize.STRING(128),
allowNull: false,
defaultValue: '',
comment: '分组名称(groupName)',
},
description: {
type: Sequelize.TEXT,
allowNull: true,
comment: '接口说明',
},
is_need_login: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 1,
comment: '是否需登录',
},
is_need_auth: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否需权限鉴权',
},
headers: {
type: Sequelize.TEXT('long'),
allowNull: true,
comment: '请求头(JSON 数组文本,LONGTEXT 保留原键序)',
},
params: {
type: Sequelize.TEXT('long'),
allowNull: true,
comment: '入参(JSON 数组文本,LONGTEXT 保留原键序)',
},
response: {
type: Sequelize.TEXT('long'),
allowNull: true,
comment: '响应字段(JSON 数组文本,LONGTEXT 保留原键序)',
},
errors: {
type: Sequelize.TEXT('long'),
allowNull: true,
comment: '错误码(JSON 数组文本,LONGTEXT 保留原键序)',
},
group_sort: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0,
comment: '分组排序(导入时的原始顺序)',
},
item_sort: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0,
comment: '组内排序(导入时的原始顺序)',
},
status: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 1,
comment: '状态:1 启用 0 下线(导出时排除)',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '更新时间',
},
}, {
comment: 'API 方法文档表(methods/system.json 的库表化维护源)',
});
await queryInterface.addIndex(DOC_TABLE, [ 'method' ], {
unique: true,
name: 'uk_method',
});
await queryInterface.addIndex(DOC_TABLE, [ 'module' ], {
name: 'idx_module',
});
await queryInterface.addIndex(DOC_TABLE, [ 'status', 'module', 'group_sort', 'item_sort' ], {
name: 'idx_export_order',
});
await queryInterface.createTable(META_TABLE, {
id: {
type: Sequelize.TINYINT,
primaryKey: true,
allowNull: false,
comment: '固定 1(单行)',
},
doc_name: {
type: Sequelize.STRING(64),
allowNull: false,
unique: true,
comment: '文档名(system/qimen...)',
},
module: {
type: Sequelize.STRING(64),
allowNull: false,
defaultValue: 'system',
comment: '文档顶层 module',
},
description: {
type: Sequelize.TEXT,
allowNull: true,
comment: '文档顶层描述',
},
headers: {
type: Sequelize.TEXT('long'),
allowNull: true,
comment: '文档全局请求头(JSON 数组文本,LONGTEXT 保留原键序)',
},
version: {
type: Sequelize.STRING(32),
allowNull: false,
defaultValue: '0.3.0',
comment: '文档版本(顶层 version)',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '更新时间(顶层 updatedAt)',
},
}, {
comment: 'API 文档元信息表(docName 维度单行)',
});
},
async down(queryInterface) {
await queryInterface.dropTable(META_TABLE);
await queryInterface.dropTable(DOC_TABLE);
},
};

View File

@ -0,0 +1,49 @@
'use strict';
/**
* 文档表 JSON 列改为 LONGTEXT(2026-09-23):
* MySQL JSON 列会归一化对象键序(如 value/name → name/value),导致导出 system.json
* 与原件产生大量无意义 diff。改为 LONGTEXT 存原始 JSON 文本,导出时原样解析,保证无损往返。
*/
const DOC_TABLE = 'wms_api_method_doc';
const META_TABLE = 'wms_method_doc_meta';
module.exports = {
async up(queryInterface, Sequelize) {
const columns = [
[ 'headers', '请求头(JSON 数组文本)' ],
[ 'params', '入参(JSON 数组文本)' ],
[ 'response', '响应字段(JSON 数组文本)' ],
[ 'errors', '错误码(JSON 数组文本)' ],
];
for (const [ name, comment ] of columns) {
await queryInterface.changeColumn(DOC_TABLE, name, {
type: Sequelize.TEXT('long'),
allowNull: true,
comment,
});
}
await queryInterface.changeColumn(META_TABLE, 'headers', {
type: Sequelize.TEXT('long'),
allowNull: true,
comment: '文档全局请求头(JSON 数组文本)',
});
},
async down(queryInterface, Sequelize) {
const columns = [ 'headers', 'params', 'response', 'errors' ];
for (const name of columns) {
await queryInterface.changeColumn(DOC_TABLE, name, {
type: Sequelize.JSON,
allowNull: true,
comment: name,
});
}
await queryInterface.changeColumn(META_TABLE, 'headers', {
type: Sequelize.JSON,
allowNull: true,
comment: '文档全局请求头(JSON 数组)',
});
},
};

View File

@ -0,0 +1,25 @@
'use strict';
/**
* 方法文档表增加 payload 列(2026-09-23):
* 原始条目含 status/notes/requestBody 等扩展字段,结构化列无法覆盖。
* payload 存整个 method 条目的原始 JSON 文本,导入/导出按原文无损往返;
* 结构化列(method/module/group_name/description/is_need_login/is_need_auth/headers/params/response/errors)
* 仅用于检索过滤,导出优先使用 payload。
*/
const DOC_TABLE = 'wms_api_method_doc';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn(DOC_TABLE, 'payload', {
type: Sequelize.TEXT('long'),
allowNull: true,
comment: 'method 条目完整 JSON 文本(含 status/notes/requestBody 等扩展字段,无损往返用)',
});
},
async down(queryInterface) {
await queryInterface.removeColumn(DOC_TABLE, 'payload');
},
};

View File

@ -0,0 +1,129 @@
'use strict';
/**
* methods/system.json 库表化维护脚本共用工具。
*
* 环境:`--env production` 或 `NODE_ENV=production` 走生产库;默认开发库。
* JSON 字段参数(headers/params/response/errors)支持内联 JSON 或 `@文件路径`。
*/
const fs = require('node:fs');
const path = require('node:path');
const mysql = require('mysql2/promise');
function resolveEnv(argv = process.argv) {
const idx = argv.indexOf('--env');
if (idx > -1 && argv[idx + 1] && !argv[idx + 1].startsWith('--')) {
return argv[idx + 1] === 'production' ? 'production' : 'development';
}
return process.env.NODE_ENV === 'production' ? 'production' : 'development';
}
function loadDbConfig(env) {
const dbConfig = require(path.join(__dirname, '..', 'database', 'config'));
return dbConfig[env];
}
function warnIfProduction(env) {
if (env !== 'production') return;
console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
console.log('[DB-CONFIG] ⚠ 警告:目标为【生产数据库】');
console.log('[DB-CONFIG] ⚠ 请确认这是预期环境;如属误判,请去掉 --env production 或清空 NODE_ENV。');
console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
async function createConnection(env) {
warnIfProduction(env);
const cfg = loadDbConfig(env);
return mysql.createConnection({
host: cfg.host,
port: cfg.port,
user: cfg.username,
password: cfg.password,
database: cfg.database,
charset: 'utf8mb4',
});
}
/** 简单参数解析:--key value / --flag;返回 Map。
* @param {string[]} [argv] 参数数组(默认 process.argv)。
*/
function parseArgs(argv = process.argv) {
const map = new Map();
for (let i = 2; i < argv.length; i++) {
const token = argv[i];
if (!token.startsWith('--')) continue;
const key = token.slice(2);
const next = argv[i + 1];
if (next !== undefined && !next.startsWith('--')) {
map.set(key, next);
i++;
} else {
map.set(key, '');
}
}
return map;
}
/** JSON 参数:内联 JSON 或 @文件路径。
* @param {string|undefined} value 参数值。
*/
function readJsonArg(value) {
if (value === undefined || value === null || value === '') return null;
const text = String(value);
if (text.startsWith('@')) {
return JSON.parse(fs.readFileSync(text.slice(1), 'utf8'));
}
return JSON.parse(text);
}
/** 解析 JSON 列(DB 返回 string/object 两种可能)。
* @param {string|object|null|undefined} raw 原始值。
*/
function parseJsonColumn(raw) {
if (raw === null || raw === undefined) return null;
if (typeof raw === 'object') return raw;
return JSON.parse(String(raw));
}
/** 版本号补丁位 +1:0.3.169 -> 0.3.170。
* @param {string} version 当前版本。
*/
function bumpVersion(version) {
const parts = String(version || '0.3.0').split('.');
const last = parts.length - 1;
parts[last] = String((Number(parts[last]) || 0) + 1);
return parts.join('.');
}
function today() {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
/** Date/字符串统一格式化为 YYYY-MM-DD。
* @param {Date|string} value 日期值。
*/
function formatDate(value) {
if (value instanceof Date) {
return `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`;
}
return String(value || '').slice(0, 10);
}
function fail(message) {
console.error(`[method-doc] ${message}`);
process.exit(1);
}
module.exports = {
resolveEnv,
createConnection,
parseArgs,
readJsonArg,
parseJsonColumn,
bumpVersion,
today,
formatDate,
fail,
};

View File

@ -0,0 +1,109 @@
'use strict';
/**
* 新建 API 方法文档(写入 wms_api_method_doc;建议完成后执行 method-doc-export.cjs 回写 methods/system.json)。
*
* 用法:
* node script/method-doc-create.cjs --method wechat.xxx --module wechat --group 微信模块 \
* --description "接口说明" [--login 1] [--auth 0] \
* [--headers @h.json] [--params @p.json] [--response @r.json] [--errors @e.json] \
* [--bump] [--doc system] [--env production]
*
* JSON 字段支持内联 JSON 或 @文件路径;--bump 时文档版本补丁位 +1 并更新 updatedAt。
*/
const {
resolveEnv, createConnection, parseArgs, readJsonArg, bumpVersion, today, fail,
} = require('./method-doc-common.cjs');
(async () => {
const args = parseArgs();
const env = resolveEnv();
const docName = args.get('doc') || 'system';
const method = args.get('method');
const module = args.get('module');
if (!method) fail('缺少 --method(方法名,如 wechat.xxx)');
if (!module) fail('缺少 --module(模块标识,如 wechat)');
const groupName = args.get('group') || '';
const description = args.get('description') || '';
const isNeedLogin = String(args.get('login') || '1') === '1' ? 1 : 0;
const isNeedAuth = String(args.get('auth') || '0') === '1' ? 1 : 0;
const headers = readJsonArg(args.get('headers'));
const params = readJsonArg(args.get('params'));
const response = readJsonArg(args.get('response'));
const errors = readJsonArg(args.get('errors'));
const bump = args.has('bump');
const conn = await createConnection(env);
// 排序:同 module+group 沿用其 group_sort;否则取全局最大 group_sort+1
const [ groupRows ] = await conn.query(
'SELECT group_sort FROM wms_api_method_doc WHERE module=? AND group_name=? ORDER BY group_sort DESC LIMIT 1',
[ module, groupName ]
);
let groupSort;
if (groupRows[0]) {
groupSort = Number(groupRows[0].group_sort);
} else {
const [ maxRows ] = await conn.query('SELECT COALESCE(MAX(group_sort),0) AS m FROM wms_api_method_doc');
groupSort = Number(maxRows[0].m) + 1;
}
const [ itemRows ] = await conn.query(
'SELECT COALESCE(MAX(item_sort),0) AS m FROM wms_api_method_doc WHERE module=? AND group_name=?',
[ module, groupName ]
);
const itemSort = Number(itemRows[0].m) + 1;
const item = {
method,
description,
isNeedAuth: isNeedAuth === 1,
isNeedLogin: isNeedLogin === 1,
headers: headers || [],
params: params || [],
response: response || [],
errors: errors || [],
};
try {
await conn.query(
`INSERT INTO wms_api_method_doc
(method, module, group_name, description, is_need_login, is_need_auth,
headers, params, response, errors, group_sort, item_sort, status, payload)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)`,
[
method,
module,
groupName,
description,
isNeedLogin,
isNeedAuth,
JSON.stringify(headers || []),
JSON.stringify(params || []),
JSON.stringify(response || []),
JSON.stringify(errors || []),
groupSort,
itemSort,
JSON.stringify(item),
]
);
} catch (e) {
if (e && e.code === 'ER_DUP_ENTRY') {
await conn.end();
fail(`method 已存在(${method}),请用 method-doc-update.cjs 更新`);
}
throw e;
}
if (bump) {
const [ metaRows ] = await conn.query('SELECT version FROM wms_method_doc_meta WHERE doc_name=?', [ docName ]);
const next = bumpVersion(metaRows[0] ? metaRows[0].version : '0.3.0');
await conn.query('UPDATE wms_method_doc_meta SET version=?, updated_at=? WHERE doc_name=?', [ next, today(), docName ]);
console.log(`[method-doc] 文档版本已升至 ${next}`);
}
await conn.end();
console.log(`[method-doc] 已创建:${method}(module=${module} group=${groupName || '(空)'} sort=${groupSort}/${itemSort}${bump ? '' : ',未 --bump 版本未变'})(env=${env})`);
})().catch(e => fail(e.message));

View File

@ -0,0 +1,45 @@
'use strict';
/**
* 下线/删除 API 方法文档(默认软删 status=0,导出时排除;--hard 真实删除)。
*
* 用法:
* node script/method-doc-delete.cjs --method wechat.xxx --yes [--hard] [--bump] [--doc system] [--env production]
*/
const {
resolveEnv, createConnection, parseArgs, bumpVersion, today, fail,
} = require('./method-doc-common.cjs');
(async () => {
const args = parseArgs();
const env = resolveEnv();
const docName = args.get('doc') || 'system';
const method = args.get('method');
if (!method) fail('缺少 --method(方法名)');
if (!args.has('yes')) fail('危险操作:请追加 --yes 确认');
const hard = args.has('hard');
const bump = args.has('bump');
const conn = await createConnection(env);
const [ result ] = hard
? await conn.query('DELETE FROM wms_api_method_doc WHERE method=?', [ method ])
: await conn.query('UPDATE wms_api_method_doc SET status=0, updated_at=NOW() WHERE method=?', [ method ]);
if (result.affectedRows === 0) {
await conn.end();
fail(`method 不存在(${method})`);
}
if (bump) {
const [ metaRows ] = await conn.query('SELECT version FROM wms_method_doc_meta WHERE doc_name=?', [ docName ]);
const next = bumpVersion(metaRows[0] ? metaRows[0].version : '0.3.0');
await conn.query('UPDATE wms_method_doc_meta SET version=?, updated_at=? WHERE doc_name=?', [ next, today(), docName ]);
console.log(`[method-doc] 文档版本已升至 ${next}`);
}
await conn.end();
console.log(`[method-doc] 已${hard ? '真实删除' : '下线(status=0)'}:${method}(env=${env})`);
})().catch(e => fail(e.message));

View File

@ -0,0 +1,73 @@
'use strict';
/**
* 从库表重建 methods/system.json(原子写入,docs 页面仍读该文件)。
*
* 用法:
* node script/method-doc-export.cjs [--env production] [--doc system] [--file methods/system.json]
*/
const fs = require('node:fs');
const {
resolveEnv, createConnection, parseArgs, parseJsonColumn, formatDate, fail,
} = require('./method-doc-common.cjs');
(async () => {
const args = parseArgs();
const env = resolveEnv();
const docName = args.get('doc') || 'system';
const file = args.get('file') || `methods/${docName}.json`;
const conn = await createConnection(env);
const [ metaRows ] = await conn.query(
'SELECT * FROM wms_method_doc_meta WHERE doc_name=? ORDER BY id ASC LIMIT 1',
[ docName ]
);
const [ rows ] = await conn.query(
'SELECT * FROM wms_api_method_doc WHERE status=1 ORDER BY group_sort ASC, item_sort ASC, id ASC'
);
await conn.end();
const meta = metaRows[0];
// 按 (group_sort, module, group_name) 重建分组
const groups = [];
const groupIndex = new Map();
for (const row of rows) {
const key = `${row.group_sort}\u0000${row.module}\u0000${row.group_name}`;
let group = groupIndex.get(key);
if (!group) {
group = { groupName: row.group_name || '', module: row.module || '', list: [] };
groupIndex.set(key, group);
groups.push(group);
}
// 优先用 payload 原文(含 status/notes/requestBody 等扩展字段,无损往返);
// 无 payload(老数据/脚本创建未带)时按结构化列组装
const parsedPayload = row.payload ? parseJsonColumn(row.payload) : null;
group.list.push(parsedPayload || {
method: row.method,
description: row.description || '',
isNeedAuth: !!row.is_need_auth,
isNeedLogin: !!row.is_need_login,
headers: parseJsonColumn(row.headers) || [],
params: parseJsonColumn(row.params) || [],
response: parseJsonColumn(row.response) || [],
errors: parseJsonColumn(row.errors) || [],
});
}
const doc = {
module: (meta && meta.module) || docName,
description: (meta && meta.description) || '',
version: (meta && meta.version) || '0.3.0',
updatedAt: meta ? formatDate(meta.updated_at) : new Date().toISOString().slice(0, 10),
headers: parseJsonColumn(meta && meta.headers) || [],
methods: { groups },
};
const tmp = `${file}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(doc, null, 4) + '\n', 'utf8');
fs.renameSync(tmp, file);
console.log(`[method-doc] 导出完成:file=${file} version=${doc.version} updatedAt=${doc.updatedAt} groups=${groups.length} methods=${rows.length}(env=${env})`);
})().catch(e => fail(e.message));

46
script/method-doc-get.cjs Normal file
View File

@ -0,0 +1,46 @@
'use strict';
/**
* 查询单个 API 方法文档(pretty JSON)。
*
* 用法:
* node script/method-doc-get.cjs --method wechat.userList [--env production]
*/
const {
resolveEnv, createConnection, parseArgs, parseJsonColumn, fail,
} = require('./method-doc-common.cjs');
(async () => {
const args = parseArgs();
const env = resolveEnv();
const method = args.get('method');
if (!method) fail('缺少 --method(方法名)');
const conn = await createConnection(env);
const [ rows ] = await conn.query('SELECT * FROM wms_api_method_doc WHERE method=? LIMIT 1', [ method ]);
await conn.end();
if (!rows[0]) fail(`method 不存在(${method})`);
const row = rows[0];
const item = row.payload ? parseJsonColumn(row.payload) : {
method: row.method,
description: row.description || '',
isNeedAuth: !!row.is_need_auth,
isNeedLogin: !!row.is_need_login,
headers: parseJsonColumn(row.headers) || [],
params: parseJsonColumn(row.params) || [],
response: parseJsonColumn(row.response) || [],
errors: parseJsonColumn(row.errors) || [],
};
const out = {
...item,
module: row.module,
group_name: row.group_name,
group_sort: Number(row.group_sort),
item_sort: Number(row.item_sort),
status: Number(row.status),
updated_at: row.updated_at,
};
console.log(JSON.stringify(out, null, 2));
})().catch(e => fail(e.message));

View File

@ -0,0 +1,86 @@
'use strict';
/**
* 将 methods/system.json 全量导入库表(wms_method_doc_meta + wms_api_method_doc,按 method upsert)。
*
* 用法:
* node script/method-doc-import.cjs [--env production] [--doc system] [--file methods/system.json]
*/
const fs = require('node:fs');
const {
resolveEnv, createConnection, parseArgs, today, fail,
} = require('./method-doc-common.cjs');
(async () => {
const args = parseArgs();
const env = resolveEnv();
const docName = args.get('doc') || 'system';
const file = args.get('file') || `methods/${docName}.json`;
const doc = JSON.parse(fs.readFileSync(file, 'utf8'));
if (!doc.methods || !Array.isArray(doc.methods.groups)) {
fail(`不支持的文档结构:${file} 缺少 methods.groups`);
}
const groups = doc.methods.groups || [];
const conn = await createConnection(env);
// 1. 元信息 upsert
await conn.query(
`INSERT INTO wms_method_doc_meta (id, doc_name, module, description, headers, version, updated_at)
VALUES (1, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE module=VALUES(module), description=VALUES(description),
headers=VALUES(headers), version=VALUES(version), updated_at=VALUES(updated_at)`,
[
docName,
doc.module || docName,
doc.description || '',
JSON.stringify(doc.headers || []),
doc.version || '0.3.0',
doc.updatedAt || today(),
]
);
// 2. 方法文档 upsert(保留原始分组/组内顺序)
const upsertSql = `
INSERT INTO wms_api_method_doc
(method, module, group_name, description, is_need_login, is_need_auth,
headers, params, response, errors, group_sort, item_sort, status, payload)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
ON DUPLICATE KEY UPDATE
module=VALUES(module), group_name=VALUES(group_name), description=VALUES(description),
is_need_login=VALUES(is_need_login), is_need_auth=VALUES(is_need_auth),
headers=VALUES(headers), params=VALUES(params), response=VALUES(response),
errors=VALUES(errors), group_sort=VALUES(group_sort), item_sort=VALUES(item_sort),
status=1, payload=VALUES(payload)`;
let upserted = 0;
for (let g = 0; g < groups.length; g++) {
const group = groups[g];
const list = Array.isArray(group.list) ? group.list : [];
for (let i = 0; i < list.length; i++) {
const item = list[i];
if (!item || !item.method) continue;
await conn.query(upsertSql, [
item.method,
group.module || '',
group.groupName || '',
item.description || '',
item.isNeedLogin ? 1 : 0,
item.isNeedAuth ? 1 : 0,
JSON.stringify(item.headers || []),
JSON.stringify(item.params || []),
JSON.stringify(item.response || []),
JSON.stringify(item.errors || []),
g,
i,
JSON.stringify(item),
]);
upserted++;
}
}
await conn.end();
console.log(`[method-doc] 导入完成:doc=${docName} file=${file} groups=${groups.length} methods=${upserted}(env=${env})`);
})().catch(e => fail(e.message));

View File

@ -0,0 +1,49 @@
'use strict';
/**
* 列出 API 方法文档(支持按模块/关键字过滤)。
*
* 用法:
* node script/method-doc-list.cjs [--module wechat] [--search 用户须知] [--env production]
*/
const {
resolveEnv, createConnection, parseArgs, fail,
} = require('./method-doc-common.cjs');
(async () => {
const args = parseArgs();
const env = resolveEnv();
const module = args.get('module');
const search = args.get('search');
const conditions = [];
const values = [];
if (module) {
conditions.push('module=?');
values.push(module);
}
if (search) {
conditions.push('(method LIKE ? OR description LIKE ? OR group_name LIKE ?)');
const kw = `%${search}%`;
values.push(kw, kw, kw);
}
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
const conn = await createConnection(env);
const [ rows ] = await conn.query(
`SELECT method, module, group_name, is_need_login, is_need_auth, status, group_sort, item_sort
FROM wms_api_method_doc ${where}
ORDER BY group_sort ASC, item_sort ASC, id ASC`,
values
);
await conn.end();
console.log(`method count: ${rows.length}`);
for (const row of rows) {
console.log(
`${String(row.method).padEnd(48)} | ${String(row.module).padEnd(18)} | ${String(row.group_name).padEnd(16)}`
+ ` | login=${row.is_need_login} auth=${row.is_need_auth} status=${row.status}`
);
}
})().catch(e => fail(e.message));

View File

@ -0,0 +1,100 @@
'use strict';
/**
* 更新 API 方法文档(部分更新;建议完成后执行 method-doc-export.cjs 回写 methods/system.json)。
*
* 用法:
* node script/method-doc-update.cjs --method wechat.xxx \
* [--module wechat] [--group 微信模块] [--description "新说明"] \
* [--login 1|0] [--auth 1|0] [--status 1|0] \
* [--headers @h.json] [--params @p.json] [--response @r.json] [--errors @e.json] \
* [--bump] [--doc system] [--env production]
*
* 至少提供除 --method/--env/--doc 外的一个字段;JSON 字段支持内联 JSON 或 @文件路径。
*/
const {
resolveEnv, createConnection, parseArgs, readJsonArg, parseJsonColumn, bumpVersion, today, fail,
} = require('./method-doc-common.cjs');
(async () => {
const args = parseArgs();
const env = resolveEnv();
const docName = args.get('doc') || 'system';
const method = args.get('method');
if (!method) fail('缺少 --method(方法名)');
const updates = [];
const values = [];
const push = (column, value) => {
updates.push(`${column}=?`);
values.push(value);
};
if (args.has('description')) push('description', args.get('description') || '');
if (args.has('module')) push('module', args.get('module'));
if (args.has('group')) push('group_name', args.get('group') || '');
if (args.has('login')) push('is_need_login', String(args.get('login')) === '1' ? 1 : 0);
if (args.has('auth')) push('is_need_auth', String(args.get('auth')) === '1' ? 1 : 0);
if (args.has('status')) push('status', String(args.get('status')) === '1' ? 1 : 0);
if (args.has('headers')) push('headers', JSON.stringify(readJsonArg(args.get('headers')) || []));
if (args.has('params')) push('params', JSON.stringify(readJsonArg(args.get('params')) || []));
if (args.has('response')) push('response', JSON.stringify(readJsonArg(args.get('response')) || []));
if (args.has('errors')) push('errors', JSON.stringify(readJsonArg(args.get('errors')) || []));
if (updates.length === 0) {
fail('未提供任何要更新的字段(description/module/group/login/auth/status/headers/params/response/errors)');
}
const bump = args.has('bump');
const conn = await createConnection(env);
// 读取当前行,payload 原文基础上应用变更(保持未改字段原键序)
const [ currentRows ] = await conn.query(
'SELECT method, module, group_name, description, is_need_login, is_need_auth, headers, params, response, errors, payload FROM wms_api_method_doc WHERE method=? LIMIT 1',
[ method ]
);
if (!currentRows[0]) {
await conn.end();
fail(`method 不存在(${method}),请先用 method-doc-create.cjs 创建`);
}
const current = currentRows[0];
const item = current.payload ? parseJsonColumn(current.payload) : {
method: current.method,
description: current.description || '',
isNeedAuth: !!current.is_need_auth,
isNeedLogin: !!current.is_need_login,
headers: parseJsonColumn(current.headers) || [],
params: parseJsonColumn(current.params) || [],
response: parseJsonColumn(current.response) || [],
errors: parseJsonColumn(current.errors) || [],
};
if (args.has('description')) item.description = args.get('description') || '';
if (args.has('login')) item.isNeedLogin = String(args.get('login')) === '1';
if (args.has('auth')) item.isNeedAuth = String(args.get('auth')) === '1';
if (args.has('headers')) item.headers = readJsonArg(args.get('headers')) || [];
if (args.has('params')) item.params = readJsonArg(args.get('params')) || [];
if (args.has('response')) item.response = readJsonArg(args.get('response')) || [];
if (args.has('errors')) item.errors = readJsonArg(args.get('errors')) || [];
const [ result ] = await conn.query(
`UPDATE wms_api_method_doc SET ${updates.join(', ')}, updated_at=NOW(), payload=? WHERE method=?`,
[ ...values, JSON.stringify(item), method ]
);
if (result.affectedRows === 0) {
await conn.end();
fail(`method 不存在(${method})`);
}
if (bump) {
const [ metaRows ] = await conn.query('SELECT version FROM wms_method_doc_meta WHERE doc_name=?', [ docName ]);
const next = bumpVersion(metaRows[0] ? metaRows[0].version : '0.3.0');
await conn.query('UPDATE wms_method_doc_meta SET version=?, updated_at=? WHERE doc_name=?', [ next, today(), docName ]);
console.log(`[method-doc] 文档版本已升至 ${next}`);
}
await conn.end();
console.log(`[method-doc] 已更新:${method}(字段:${updates.map(u => u.split('=')[0]).join('/')}${bump ? '' : ',未 --bump 版本未变'})(env=${env})`);
})().catch(e => fail(e.message));