200 lines
7.8 KiB
TypeScript
200 lines
7.8 KiB
TypeScript
/**
|
||
* 「一行一个参数」的表格与后端那几份 JSON 对象之间的翻译层。
|
||
*
|
||
* 后端存的还是 ``headers`` / ``bodyTemplate`` / ``mapExtra`` 三份对象——执行器照旧直接
|
||
* 拿去发请求,一处都不用改。界面上它们是一张表格,表格比对象多出来两样东西:
|
||
* 这一行勾没勾用、给人看的备注。这两样单独记在 ``paramMeta`` 里,不进报文,
|
||
* 也不动那三份对象的形状(停用的行干脆不写进去,取数时自然不会发)。
|
||
*
|
||
* ``ParamMeta`` 这几份是发给后端的形状,所以和别的接口类型一起放在 types 里。
|
||
*/
|
||
import type { ParamMeta, ParamMetaEntry } from '@/types'
|
||
|
||
/** 表格里的参数。 */
|
||
export interface ParamRow {
|
||
/** 取消勾选 = 这一行不进请求,但行还留在表格里,随时能勾回来 */
|
||
enabled: boolean
|
||
key: string
|
||
value: string
|
||
/** 备注只给配表的人看,不进报文 */
|
||
note: string
|
||
}
|
||
|
||
/** 一行没填出来的问题;``code`` 交给界面翻译,这里不写人话。 */
|
||
export interface ParamIssue {
|
||
/** 出问题的行号 */
|
||
index: number
|
||
code: 'emptyKey' | 'duplicate' | 'caseDuplicate' | 'reserved' | 'noValue'
|
||
params?: Record<string, string | number>
|
||
}
|
||
|
||
export interface ParamIssueOptions {
|
||
/** 请求头不区分大小写,``accept`` 写两遍上游只认一份 */
|
||
caseInsensitive?: boolean
|
||
/** 这些键由别的地方生成(如 Authorization 来自鉴权方式那一栏),写在这儿会被覆盖 */
|
||
reserved?: string[]
|
||
/** 空值算不算问题:入参里 ``keyword: ''`` 是合法写法,请求头里空值基本是笔误 */
|
||
emptyValueIsIssue?: boolean
|
||
}
|
||
|
||
export function newParamRow(key = '', value = '', note = '', enabled = true): ParamRow {
|
||
return { enabled, key, value, note }
|
||
}
|
||
|
||
/** 空表格里也要有一行能直接敲,省一次「加一行」点击。 */
|
||
export function paramRowsWithBlankRow(rows: ParamRow[]): ParamRow[] {
|
||
const list = rows.length ? rows : [newParamRow()]
|
||
const last = list[list.length - 1]
|
||
return last.key.trim() || last.value.trim() ? [...list, newParamRow()] : list
|
||
}
|
||
|
||
/**
|
||
* 表格里的值 → 模板里的值。
|
||
*
|
||
* 整格写成一段合法 JSON(``{"size": 10}``)就按结构存,上游那种带嵌套的请求体才配得出来;
|
||
* 取值写法 ``{arg.year}`` 不是合法 JSON,照旧是字符串。老版本把非字符串的值
|
||
* ``String()`` 成了 ``[object Object]``,一开一存就把配置毁了,这一版顺手修掉。
|
||
*/
|
||
export function templateValue(text: string): unknown {
|
||
const trimmed = text.trim()
|
||
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
||
try {
|
||
return JSON.parse(trimmed)
|
||
} catch {
|
||
// 十有八九是 {arg.year} 这种没引号的写法,按字符串发就对了
|
||
}
|
||
}
|
||
return text
|
||
}
|
||
|
||
function displayValue(value: unknown): string {
|
||
if (typeof value === 'string') return value
|
||
if (value === null || value === undefined) return ''
|
||
return JSON.stringify(value)
|
||
}
|
||
|
||
/**
|
||
* 后端那份对象 + 备注 → 表格行。
|
||
*
|
||
* 停用的行不在对象里,只能靠备注里那份 ``off`` 记着,所以排在末尾:
|
||
* 打开弹窗时「上面是在发的,下面几行是没勾的」,比混在一起好读。
|
||
*/
|
||
export function rowsFromRecord(record?: Record<string, unknown> | null, meta?: ParamMeta | null): ParamRow[] {
|
||
const rows = Object.entries(record ?? {}).map(([key, value]) => ({
|
||
enabled: meta?.[key]?.off !== true,
|
||
key,
|
||
value: displayValue(value),
|
||
note: meta?.[key]?.note ?? ''
|
||
}))
|
||
const present = new Set(rows.map((row) => row.key))
|
||
Object.entries(meta ?? {}).forEach(([key, entry]) => {
|
||
if (entry?.off && !present.has(key)) rows.push(newParamRow(key, entry.value ?? '', entry.note ?? '', false))
|
||
})
|
||
return rows
|
||
}
|
||
|
||
/** 表格行 → 送给后端的那份对象(没勾的行不在里面)。 */
|
||
export function recordFromRows(rows: ParamRow[]): Record<string, unknown> {
|
||
const out: Record<string, unknown> = {}
|
||
rows.forEach((row) => {
|
||
const key = row.key.trim()
|
||
if (row.enabled && key) out[key] = templateValue(row.value)
|
||
})
|
||
return out
|
||
}
|
||
|
||
/** 请求头与可带出键只认字符串,走这一条。 */
|
||
export function stringRecordFromRows(rows: ParamRow[]): Record<string, string> {
|
||
const out: Record<string, string> = {}
|
||
rows.forEach((row) => {
|
||
const key = row.key.trim()
|
||
if (row.enabled && key) out[key] = row.value
|
||
})
|
||
return out
|
||
}
|
||
|
||
/** 表格行 → 备注(只记真正多出来的信息,能省则省)。 */
|
||
export function metaFromRows(rows: ParamRow[]): ParamMeta {
|
||
const out: ParamMeta = {}
|
||
rows.forEach((row) => {
|
||
const key = row.key.trim()
|
||
if (!key) return
|
||
const entry: ParamMetaEntry = {}
|
||
if (!row.enabled) {
|
||
entry.off = true
|
||
entry.value = row.value
|
||
}
|
||
if (row.note.trim()) entry.note = row.note.trim()
|
||
if (Object.keys(entry).length) out[key] = entry
|
||
})
|
||
return out
|
||
}
|
||
|
||
/** 这一份参数一共声明了哪些入参(``{arg.x}`` / ``{form.x}``),给测试面板和提示用。 */
|
||
export function referencedParams(value: unknown, found = new Set<string>()): Set<string> {
|
||
if (typeof value === 'string') {
|
||
for (const match of value.matchAll(/\{(?:arg|form)[.:]\s*([^}]+?)\s*\}/g)) found.add(match[1])
|
||
} else if (Array.isArray(value)) {
|
||
value.forEach((item) => referencedParams(item, found))
|
||
} else if (value && typeof value === 'object') {
|
||
Object.values(value).forEach((item) => referencedParams(item, found))
|
||
}
|
||
return found
|
||
}
|
||
|
||
/** 行里的毛病:重复键、只有值没有键、被别处覆盖的键。返回码,由界面翻译成人话。 */
|
||
export function paramIssues(rows: ParamRow[], options: ParamIssueOptions = {}): ParamIssue[] {
|
||
const issues: ParamIssue[] = []
|
||
const seen = new Map<string, number>()
|
||
const reserved = new Set((options.reserved ?? []).map((key) => key.trim().toLowerCase()).filter(Boolean))
|
||
rows.forEach((row, index) => {
|
||
const key = row.key.trim()
|
||
if (!key) {
|
||
if (row.value.trim() || row.note.trim()) issues.push({ index, code: 'emptyKey' })
|
||
return
|
||
}
|
||
const dedupeKey = options.caseInsensitive ? key.toLowerCase() : key
|
||
const first = seen.get(dedupeKey)
|
||
if (first !== undefined) {
|
||
issues.push({ index, code: options.caseInsensitive ? 'caseDuplicate' : 'duplicate', params: { key, first: first + 1 } })
|
||
return
|
||
}
|
||
seen.set(dedupeKey, index)
|
||
// 请求头名不分大小写,鉴权那栏写 Authorization 还是 authorization 都算撞上
|
||
if (reserved.has(key.toLowerCase())) issues.push({ index, code: 'reserved', params: { key } })
|
||
else if (options.emptyValueIsIssue && !row.value.trim()) issues.push({ index, code: 'noValue', params: { key } })
|
||
})
|
||
return issues
|
||
}
|
||
|
||
/** 批量编辑那一段文本:一行一条,``名: 值``,行首 ``#`` 表示先停用。 */
|
||
export function rowsToBulk(rows: ParamRow[]): string {
|
||
return rows
|
||
.filter((row) => row.key.trim())
|
||
.map((row) => `${row.enabled ? '' : '# '}${row.key.trim()}: ${row.value}`)
|
||
.join('\n')
|
||
}
|
||
|
||
/**
|
||
* 批量文本 → 表格行,备注按参数名从原来那几行接着用。
|
||
*
|
||
* 批量那一栏装不下备注,直接覆盖会把人写好的说明擦掉;同名行留旧备注,
|
||
* 新加的行没备注,删掉的行整行消失,这样来回切不丢东西。
|
||
*/
|
||
export function bulkToRows(text: string, previous: ParamRow[]): ParamRow[] {
|
||
const notes = new Map(previous.map((row) => [row.key.trim(), row.note]))
|
||
const rows: ParamRow[] = []
|
||
text.split(/\r?\n/).forEach((line) => {
|
||
const raw = line.trim()
|
||
if (!raw) return
|
||
const off = raw.startsWith('#')
|
||
const body = raw.replace(/^#+\s*/, '')
|
||
const cut = body.indexOf(':')
|
||
if (cut < 0) return
|
||
const key = body.slice(0, cut).trim()
|
||
if (!key) return
|
||
rows.push(newParamRow(key, body.slice(cut + 1).trim(), notes.get(key) ?? '', !off))
|
||
})
|
||
return rows
|
||
}
|