contractDiff.js
4.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
const fs = require("fs");
const path = require("path");
const { buildContract, toMethodFileName } = require("./swaggerInspect");
const ADAPTERS_GLOB_ROOT = path.join(__dirname, "../../api/adapters");
function normalizeParams(parameters = []) {
return parameters
.filter((p) => p.in === "query" && p.name !== "sessionId")
.map((p) => ({
name: p.name,
type: p.type || "",
required: !!p.required,
}))
.sort((a, b) => a.name.localeCompare(b.name));
}
function normalizeResponse(contract = {}) {
return {
hasPagination: !!contract.response?.pagination,
paginationFields: contract.response?.pagination?.fields || [],
fieldNames: (contract.response?.fields || [])
.filter((f) => !f.name.includes("."))
.map((f) => f.name.split(".").pop())
.filter((name) => name !== "code" && name !== "message"),
};
}
function findTrackedContracts(rootDir = ADAPTERS_GLOB_ROOT) {
const results = [];
if (!fs.existsSync(rootDir)) {
return results;
}
function walk(dir) {
fs.readdirSync(dir, { withFileTypes: true }).forEach((entry) => {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
walk(fullPath);
return;
}
if (entry.isFile() && entry.name.endsWith(".contract.json")) {
const raw = JSON.parse(fs.readFileSync(fullPath, "utf8"));
results.push({
filePath: fullPath,
method: raw.method,
contract: raw,
});
}
});
}
walk(rootDir);
return results;
}
function compareContracts(tracked, fresh) {
const errors = [];
const warnings = [];
const trackedParams = normalizeParams(tracked.request?.parameters);
const freshParams = normalizeParams(fresh.request?.parameters);
const trackedMap = new Map(trackedParams.map((p) => [p.name, p]));
const freshMap = new Map(freshParams.map((p) => [p.name, p]));
trackedParams.forEach((param) => {
if (!freshMap.has(param.name)) {
errors.push(`请求参数已删除: ${param.name}`);
}
});
freshParams.forEach((param) => {
const old = trackedMap.get(param.name);
if (!old) {
if (param.required) {
errors.push(`新增必填请求参数: ${param.name}`);
} else {
warnings.push(`新增可选请求参数: ${param.name}`);
}
return;
}
if (old.required !== param.required && param.required) {
errors.push(`请求参数变为必填: ${param.name}`);
}
if (old.type && param.type && old.type !== param.type) {
warnings.push(`请求参数类型变更: ${param.name} (${old.type} -> ${param.type})`);
}
});
const trackedResponse = normalizeResponse(tracked);
const freshResponse = normalizeResponse(fresh);
if (trackedResponse.hasPagination && !freshResponse.hasPagination) {
errors.push("响应分页结构消失");
}
if (trackedResponse.hasPagination && !freshResponse.paginationFields.includes("list")) {
errors.push("分页响应缺少 list 字段");
}
trackedResponse.fieldNames.forEach((name) => {
if (!freshResponse.fieldNames.includes(name)) {
warnings.push(`响应字段可能移除: ${name}`);
}
});
freshResponse.fieldNames.forEach((name) => {
if (!trackedResponse.fieldNames.includes(name)) {
warnings.push(`新增响应字段: ${name}`);
}
});
return { errors, warnings };
}
function diffSnapshotWithTracked(swagger, trackedItems) {
const report = {
errors: [],
warnings: [],
checked: 0,
};
trackedItems.forEach((item) => {
report.checked += 1;
let fresh;
try {
fresh = buildContract(swagger, item.method);
} catch (error) {
report.errors.push(`${item.method}: method 在快照中不存在 (${error.message})`);
return;
}
const { errors, warnings } = compareContracts(item.contract, fresh);
errors.forEach((message) => report.errors.push(`${item.method}: ${message}`));
warnings.forEach((message) => report.warnings.push(`${item.method}: ${message}`));
});
return report;
}
function diffOnlineSnapshot(oldSwagger, newSwagger) {
const report = {
errors: [],
warnings: [],
added: [],
removed: [],
};
const oldMethods = new Set(Object.keys(oldSwagger.paths || {})
.filter((route) => route.startsWith("/router/"))
.map((route) => route.slice("/router/".length, -"/1.0.0".length)));
const newMethods = new Set(Object.keys(newSwagger.paths || {})
.filter((route) => route.startsWith("/router/"))
.map((route) => route.slice("/router/".length, -"/1.0.0".length)));
oldMethods.forEach((method) => {
if (!newMethods.has(method)) {
report.removed.push(method);
}
});
newMethods.forEach((method) => {
if (!oldMethods.has(method)) {
report.added.push(method);
}
});
if (report.removed.length) {
report.warnings.push(`快照相比线上减少 ${report.removed.length} 个 method,建议 npm run rop:swagger:fetch`);
}
if (report.added.length) {
report.warnings.push(`快照相比线上新增 ${report.added.length} 个 method,建议 npm run rop:swagger:fetch`);
}
return report;
}
module.exports = {
findTrackedContracts,
compareContracts,
diffSnapshotWithTracked,
diffOnlineSnapshot,
normalizeParams,
toMethodFileName,
ADAPTERS_GLOB_ROOT,
};