mm_datas 0.0.0-stage → 5.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/example/custom_demo.js +237 -0
- package/example/model/item_model.json +46 -0
- package/example/model/map_model.json +53 -0
- package/example/model/player_model.json +65 -0
- package/example/model/role_model.json +61 -0
- package/example/model/skill_model.json +60 -0
- package/example/preset_demo.js +44 -0
- package/example/rpg_cache.js +179 -0
- package/example/rpg_crud.js +170 -0
- package/example/rpg_demo.js +61 -0
- package/example/rpg_model/bag_model.json +74 -0
- package/example/rpg_model/character_model.json +165 -0
- package/example/rpg_model/character_skill_model.json +61 -0
- package/example/rpg_model/drop_model.json +103 -0
- package/example/rpg_model/item_model.json +189 -0
- package/example/rpg_model/job_model.json +96 -0
- package/example/rpg_model/level_exp_model.json +111 -0
- package/example/rpg_model/map_model.json +166 -0
- package/example/rpg_model/map_state_model.json +63 -0
- package/example/rpg_model/monster_model.json +115 -0
- package/example/rpg_model/npc_model.json +103 -0
- package/example/rpg_model/quest_model.json +106 -0
- package/example/rpg_model/quest_progress_model.json +61 -0
- package/example/rpg_model/save_model.json +42 -0
- package/example/rpg_model/skill_model.json +124 -0
- package/example/rpg_persistence.js +151 -0
- package/example/rpg_relations.js +196 -0
- package/example/rpg_world.js +149 -0
- package/example/storage_demo.js +194 -0
- package/index.js +122 -0
- package/lib/backend.js +597 -0
- package/lib/errors.js +35 -0
- package/lib/manager.js +717 -0
- package/lib/model.js +540 -0
- package/lib/pool.js +277 -0
- package/lib/relation.js +175 -0
- package/lib/store.js +430 -0
- package/package.json +64 -5
- package/test.js +748 -0
- package/tool/data/index.js +107 -0
- package/tool/data/tool.json +211 -0
- package/README.md +0 -3
package/lib/model.js
ADDED
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 集合定义归一化 + 「标准 JSON Schema → mm_validator 规则」编译。
|
|
5
|
+
*
|
|
6
|
+
* model.schema 是一份标准 JSON Schema(draft-07 子集,写法与仓库 tool.json 的 params 一致):
|
|
7
|
+
* {
|
|
8
|
+
* "$schema": "http://json-schema.org/draft-07/schema#",
|
|
9
|
+
* "type": "object",
|
|
10
|
+
* "properties": {
|
|
11
|
+
* "name": { "type": "string", "maxLength": 12 },
|
|
12
|
+
* "level": { "type": "number", "minimum": 1, "maximum": 99 },
|
|
13
|
+
* "attrs": { "type": "object", "properties": { ... }, "required": [...] },
|
|
14
|
+
* "tags": { "type": "array", "items": { "type": "string" }, "maxItems": 3 }
|
|
15
|
+
* },
|
|
16
|
+
* "required": ["name"],
|
|
17
|
+
* "additionalProperties": false
|
|
18
|
+
* }
|
|
19
|
+
*
|
|
20
|
+
* 标准关键词:type / required / enum / const / minimum / maximum /
|
|
21
|
+
* exclusiveMinimum / exclusiveMaximum / minLength / maxLength /
|
|
22
|
+
* minItems / maxItems / pattern / properties / items / additionalProperties / default / description
|
|
23
|
+
* mm_data 扩展关键词(标准校验器会忽略,仅用于模块自身的元数据):
|
|
24
|
+
* primary / auto / ref / snapshot / index
|
|
25
|
+
*
|
|
26
|
+
* 类型白名单:string / number / boolean / object / array / null。
|
|
27
|
+
* 明确不接受 int / integer / any —— 统一使用 number。定义时即抛 SCHEMA_TYPE_UNSUPPORTED。
|
|
28
|
+
* 原因:规则判定全部委托 mm_validator,而其 params / type 工具只认 JS 原生 typeof 类型,
|
|
29
|
+
* 写一个无法被判定的整数类型只会造成「看起来有约束、实际没校验」。
|
|
30
|
+
*
|
|
31
|
+
* 职责边界:本文件不做任何规则判定,只做
|
|
32
|
+
* ① 标准关键词 → mm_validator/tool/params 的 rules 翻译;
|
|
33
|
+
* ② 递归遍历 properties / items 并拼接错误路径;
|
|
34
|
+
* ③ additionalProperties:false 的字段清单比对(结构性,非规则判定);
|
|
35
|
+
* ④ 空串补检(params 会跳过空值,改用 length / pattern / enum / type 工具)。
|
|
36
|
+
* 所有类型、范围、长度、正则、枚举的判定均由 mm_validator 的工具执行。
|
|
37
|
+
*/
|
|
38
|
+
const path = require('path');
|
|
39
|
+
const { raise } = require('./errors.js');
|
|
40
|
+
|
|
41
|
+
const DRAFT = 'http://json-schema.org/draft-07/schema#';
|
|
42
|
+
const ALLOWED_TYPES = ['string', 'number', 'boolean', 'object', 'array', 'null'];
|
|
43
|
+
// 非标准或无法由 mm_validator 判定的类型 → 提示改用的标准类型
|
|
44
|
+
const FORBIDDEN_TYPES = {
|
|
45
|
+
int: 'number', integer: 'number', any: null,
|
|
46
|
+
float: 'number', long: 'number', double: 'number', bigint: 'number'
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
let V = null;
|
|
50
|
+
let V_ERROR = null;
|
|
51
|
+
try {
|
|
52
|
+
V = require('mm_validator');
|
|
53
|
+
} catch (e) {
|
|
54
|
+
V_ERROR = e.message;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const TOOLS = {};
|
|
58
|
+
const CALLS = { total: 0, by_tool: {} };
|
|
59
|
+
|
|
60
|
+
function tool(name) {
|
|
61
|
+
if (!V) {
|
|
62
|
+
raise('VALIDATOR_MISSING', 'schema 校验依赖 mm_validator:模块未安装或无法解析' +
|
|
63
|
+
(V_ERROR ? '(' + V_ERROR + ')' : ''));
|
|
64
|
+
}
|
|
65
|
+
if (!TOOLS[name]) {
|
|
66
|
+
try {
|
|
67
|
+
TOOLS[name] = require(path.join(V.TOOL_DIR, name));
|
|
68
|
+
} catch (e) {
|
|
69
|
+
raise('VALIDATOR_MISSING', '无法加载 mm_validator/tool/' + name + ':' + e.message);
|
|
70
|
+
}
|
|
71
|
+
if (!TOOLS[name] || typeof TOOLS[name].main !== 'function') {
|
|
72
|
+
raise('VALIDATOR_MISSING', 'mm_validator/tool/' + name + ' 未导出 main');
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return TOOLS[name];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 调用一个 mm_validator 工具;工具当前同步写 ctx.output,若未来异步化则明确报错而非放行 */
|
|
79
|
+
function run(name, params) {
|
|
80
|
+
const ctx = { output: null };
|
|
81
|
+
let ret = null;
|
|
82
|
+
try {
|
|
83
|
+
ret = tool(name).main(params, ctx, {});
|
|
84
|
+
} catch (e) {
|
|
85
|
+
raise('VALIDATOR_ERROR', 'mm_validator/' + name + ' 执行失败:' + e.message);
|
|
86
|
+
}
|
|
87
|
+
CALLS.total++;
|
|
88
|
+
CALLS.by_tool[name] = (CALLS.by_tool[name] || 0) + 1;
|
|
89
|
+
if (ret && typeof ret.then === 'function') ret.catch(function () {});
|
|
90
|
+
if (!ctx.output) {
|
|
91
|
+
raise('VALIDATOR_ERROR', 'mm_validator/' + name + ' 未同步返回校验结果(工具已异步化,需同步适配)');
|
|
92
|
+
}
|
|
93
|
+
return ctx.output;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function clone(v) {
|
|
97
|
+
return v === undefined ? undefined : JSON.parse(JSON.stringify(v));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function pick(a, b, c) {
|
|
101
|
+
if (a !== undefined) return a;
|
|
102
|
+
if (b !== undefined) return b;
|
|
103
|
+
return c;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function joinPath(prefix, seg) {
|
|
107
|
+
return prefix ? prefix + '.' + seg : seg;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 递归检查类型白名单:任何 int / integer / any 在定义阶段就被拒绝 */
|
|
111
|
+
function assertTypes(def, loc) {
|
|
112
|
+
if (!def || typeof def !== 'object') return;
|
|
113
|
+
if (def.type !== undefined) {
|
|
114
|
+
const list = Array.isArray(def.type) ? def.type : [def.type];
|
|
115
|
+
for (let i = 0; i < list.length; i++) {
|
|
116
|
+
const t = list[i];
|
|
117
|
+
if (ALLOWED_TYPES.indexOf(t) === -1) {
|
|
118
|
+
const hint = FORBIDDEN_TYPES[t] ? ',请改用 "' + FORBIDDEN_TYPES[t] + '"' : '';
|
|
119
|
+
raise('SCHEMA_TYPE_UNSUPPORTED', loc + ' 使用了不支持的类型 "' + t + '"' + hint +
|
|
120
|
+
';标准 JSON Schema 允许的类型仅:' + ALLOWED_TYPES.join(' / '));
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (def.properties) {
|
|
125
|
+
for (const f in def.properties) assertTypes(def.properties[f], loc + '.properties.' + f);
|
|
126
|
+
}
|
|
127
|
+
if (def.items) assertTypes(def.items, loc + '.items');
|
|
128
|
+
if (def.additionalProperties && typeof def.additionalProperties === 'object') {
|
|
129
|
+
assertTypes(def.additionalProperties, loc + '.additionalProperties');
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 把用户传入的 schema 归一成一份标准 JSON Schema 文档;undefined/null 表示自由集合 */
|
|
134
|
+
function toStandard(raw) {
|
|
135
|
+
if (raw === undefined || raw === null || raw === false) return null;
|
|
136
|
+
// 空对象表示「未定义 schema」= 自由集合,不生成约束文档
|
|
137
|
+
if (typeof raw === 'object' && !Array.isArray(raw) && Object.keys(raw).length === 0) return null;
|
|
138
|
+
|
|
139
|
+
// 简写:['name', 'level'] 或 [{ name:'name', type:'string' }]
|
|
140
|
+
if (Array.isArray(raw)) {
|
|
141
|
+
const props = {};
|
|
142
|
+
for (let i = 0; i < raw.length; i++) {
|
|
143
|
+
const it = raw[i];
|
|
144
|
+
if (typeof it === 'string') props[it] = {};
|
|
145
|
+
else if (it && it.name) {
|
|
146
|
+
const d = Object.assign({}, it);
|
|
147
|
+
delete d.name;
|
|
148
|
+
props[it.name] = d;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const js = { $schema: DRAFT, type: 'object', properties: props, required: [], additionalProperties: false };
|
|
152
|
+
assertTypes(js, 'schema');
|
|
153
|
+
return js;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (typeof raw !== 'object') return null;
|
|
157
|
+
|
|
158
|
+
const isStandard = raw.type === 'object' || !!raw.properties || !!raw.$schema || Array.isArray(raw.required);
|
|
159
|
+
if (isStandard) {
|
|
160
|
+
const js = clone(raw);
|
|
161
|
+
js.$schema = js.$schema || DRAFT;
|
|
162
|
+
js.type = 'object';
|
|
163
|
+
js.properties = js.properties || {};
|
|
164
|
+
js.required = Array.isArray(js.required) ? js.required.slice() : [];
|
|
165
|
+
js.additionalProperties = js.additionalProperties === false ? false : true;
|
|
166
|
+
assertTypes(js, 'schema');
|
|
167
|
+
return js;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// 兼容旧的扁平字段表:自动升级为标准 JSON Schema(required:true → 顶层 required 数组)
|
|
171
|
+
const props = {};
|
|
172
|
+
const required = [];
|
|
173
|
+
for (const f in raw) {
|
|
174
|
+
const src = typeof raw[f] === 'string' ? { type: raw[f] } : Object.assign({}, raw[f] || {});
|
|
175
|
+
if (src.required === true || src.not_null === true) required.push(f);
|
|
176
|
+
delete src.required;
|
|
177
|
+
delete src.not_null;
|
|
178
|
+
delete src.validator; // 自定义校验函数不属于标准 JSON Schema
|
|
179
|
+
// 旧扁平格式的私有别名统一翻译成标准关键词,保证 schema() 返回的是标准文档
|
|
180
|
+
if (src.min !== undefined) { src.minimum = src.min; delete src.min; }
|
|
181
|
+
if (src.max !== undefined) { src.maximum = src.max; delete src.max; }
|
|
182
|
+
if (src.min_length !== undefined) { src.minLength = src.min_length; delete src.min_length; }
|
|
183
|
+
if (src.max_length !== undefined) { src.maxLength = src.max_length; delete src.max_length; }
|
|
184
|
+
props[f] = src;
|
|
185
|
+
}
|
|
186
|
+
const js = { $schema: DRAFT, type: 'object', properties: props, required: required, additionalProperties: false };
|
|
187
|
+
assertTypes(js, 'schema');
|
|
188
|
+
return js;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** 字段定义:保留标准关键词,补齐模块自身的扩展元数据 */
|
|
192
|
+
function normalizeField(raw) {
|
|
193
|
+
let def = raw;
|
|
194
|
+
if (typeof def === 'string') def = { type: def };
|
|
195
|
+
else if (Array.isArray(def)) def = {};
|
|
196
|
+
def = def || {};
|
|
197
|
+
const item = Object.assign({}, def);
|
|
198
|
+
item.primary = !!def.primary;
|
|
199
|
+
item.auto = !!def.auto;
|
|
200
|
+
item.description = def.description || '';
|
|
201
|
+
item.snapshot = def.snapshot || null;
|
|
202
|
+
item.ref = def.ref
|
|
203
|
+
? (typeof def.ref === 'string'
|
|
204
|
+
? { model: def.ref, key: null, mode: 'live', onMissing: 'error' }
|
|
205
|
+
: Object.assign({ model: '', key: null, mode: 'live', onMissing: 'error' }, def.ref))
|
|
206
|
+
: null;
|
|
207
|
+
return item;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** 标准文档的 properties → 内部扁平字段表(供 default / primary / ref / verify 使用) */
|
|
211
|
+
function fieldsOf(js, props, required) {
|
|
212
|
+
const out = {};
|
|
213
|
+
if (!js) return out;
|
|
214
|
+
const src = props || js.properties || {};
|
|
215
|
+
const req = required || js.required || [];
|
|
216
|
+
for (const f in src) {
|
|
217
|
+
const raw = typeof src[f] === 'string' ? { type: src[f] } : Object.assign({}, src[f] || {});
|
|
218
|
+
const item = normalizeField(raw);
|
|
219
|
+
if (req.indexOf(f) !== -1) item.required = true;
|
|
220
|
+
out[f] = item;
|
|
221
|
+
}
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** 嵌套 object 的 properties 转成一层内部字段表 */
|
|
226
|
+
function childFields(def) {
|
|
227
|
+
const req = Array.isArray(def.required) ? def.required : [];
|
|
228
|
+
return fieldsOf({ required: req }, def.properties || {}, req);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function normalizeSchema(raw) {
|
|
232
|
+
return fieldsOf(toStandard(raw));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function findPrimary(schema) {
|
|
236
|
+
for (const f in schema) if (schema[f].primary) return f;
|
|
237
|
+
if (schema.id) return 'id';
|
|
238
|
+
if (schema._id) return '_id';
|
|
239
|
+
return 'id';
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** 运行时读写标准文档里的某个字段定义(供 DataManager.field / ref 使用) */
|
|
243
|
+
function setField(jsRaw, field, def) {
|
|
244
|
+
const js = toStandard(jsRaw) || {
|
|
245
|
+
$schema: DRAFT, type: 'object', properties: {}, required: [], additionalProperties: false
|
|
246
|
+
};
|
|
247
|
+
js.properties[field] = def === undefined ? {} : def;
|
|
248
|
+
assertTypes(js, 'schema');
|
|
249
|
+
return js;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function getField(jsRaw, field) {
|
|
253
|
+
const js = toStandard(jsRaw);
|
|
254
|
+
return js ? js.properties[field] : undefined;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** 归一化一份集合定义 */
|
|
258
|
+
function normalize(name, def) {
|
|
259
|
+
if (typeof def === 'string') def = { kind: def };
|
|
260
|
+
if (Array.isArray(def)) def = { schema: def };
|
|
261
|
+
def = def || {};
|
|
262
|
+
let kind = def.kind || (def.static ? 'static' : 'dynamic');
|
|
263
|
+
if (['static', 'dynamic', 'link'].indexOf(kind) === -1) kind = 'dynamic';
|
|
264
|
+
|
|
265
|
+
const jsonSchema = toStandard(def.schema || def.columns || def.fields || {});
|
|
266
|
+
let schema = fieldsOf(jsonSchema);
|
|
267
|
+
const store = def.store || {};
|
|
268
|
+
const key = def.key || store.key || findPrimary(schema);
|
|
269
|
+
// 主键若未在 properties 中声明,自动补一项:避免 additionalProperties:false
|
|
270
|
+
// 在 set/patch 校验「整行最终形态」时把自增主键误判为未知字段。
|
|
271
|
+
if (jsonSchema && !jsonSchema.properties[key]) {
|
|
272
|
+
jsonSchema.properties[key] = { auto: true };
|
|
273
|
+
schema = fieldsOf(jsonSchema);
|
|
274
|
+
}
|
|
275
|
+
const schemaless = Object.keys(schema).length === 0;
|
|
276
|
+
const keyDef = schema[key];
|
|
277
|
+
const auto = keyDef ? !!keyDef.auto : true;
|
|
278
|
+
const readonly = def.readonly === undefined ? (kind === 'static') : !!def.readonly;
|
|
279
|
+
const additionalProperties = jsonSchema ? jsonSchema.additionalProperties !== false : true;
|
|
280
|
+
|
|
281
|
+
const relations = [];
|
|
282
|
+
for (const field in schema) {
|
|
283
|
+
const ref = schema[field].ref;
|
|
284
|
+
if (!ref) continue;
|
|
285
|
+
relations.push({
|
|
286
|
+
name: ref.as || ref.model || field,
|
|
287
|
+
type: 'many-to-one',
|
|
288
|
+
model: ref.model,
|
|
289
|
+
local: field,
|
|
290
|
+
foreign: ref.key || null,
|
|
291
|
+
select: ref.select || null,
|
|
292
|
+
mode: ref.mode || 'live',
|
|
293
|
+
onMissing: ref.onMissing || 'error'
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
const declared = def.relations || [];
|
|
297
|
+
for (let i = 0; i < declared.length; i++) {
|
|
298
|
+
const r = declared[i];
|
|
299
|
+
relations.push({
|
|
300
|
+
name: r.name || r.as || ('rel_' + i),
|
|
301
|
+
type: r.type || 'one-to-many',
|
|
302
|
+
model: r.model,
|
|
303
|
+
via: r.via || null,
|
|
304
|
+
local: r.local || key,
|
|
305
|
+
foreign: r.foreign || null,
|
|
306
|
+
as: r.as || r.name || ('rel_' + i),
|
|
307
|
+
select: r.select || null,
|
|
308
|
+
mode: r.mode || 'live'
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
return {
|
|
313
|
+
name: name,
|
|
314
|
+
kind: kind,
|
|
315
|
+
readonly: readonly,
|
|
316
|
+
strict: !additionalProperties,
|
|
317
|
+
additionalProperties: additionalProperties,
|
|
318
|
+
constrained: !schemaless,
|
|
319
|
+
schemaless: schemaless,
|
|
320
|
+
version: def.version || 1,
|
|
321
|
+
key: key,
|
|
322
|
+
auto: auto,
|
|
323
|
+
table: def.table || store.table || name,
|
|
324
|
+
db: def.db || store.db || 'memory',
|
|
325
|
+
shard: def.shard || store.shard || null,
|
|
326
|
+
indexes: def.indexes || store.indexes || [],
|
|
327
|
+
schema: schema, // 内部扁平字段表(元数据 + 标准关键词)
|
|
328
|
+
jsonSchema: jsonSchema, // 用户定义的原始标准 JSON Schema 文档
|
|
329
|
+
relations: relations,
|
|
330
|
+
seed: def.seed || null,
|
|
331
|
+
source: def.source || null,
|
|
332
|
+
generate: def.generate || null,
|
|
333
|
+
description: def.description || '',
|
|
334
|
+
raw: def
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** 标准关键词 → mm_validator/tool/params 的单字段 rules */
|
|
339
|
+
function ruleOf(def, value) {
|
|
340
|
+
const r = {};
|
|
341
|
+
if (!def || typeof def !== 'object') return r;
|
|
342
|
+
if (def.required === true) r.required = true;
|
|
343
|
+
const t = Array.isArray(def.type) ? def.type[0] : def.type;
|
|
344
|
+
// null 无法由 params 的 typeof 判定(typeof null === 'object'),故不生成类型规则
|
|
345
|
+
if (t && t !== 'null') r.type = t;
|
|
346
|
+
const en = def.enum || (def.const !== undefined ? [def.const] : null);
|
|
347
|
+
if (en) r.enum = en;
|
|
348
|
+
if (def.pattern) r.pattern = def.pattern;
|
|
349
|
+
|
|
350
|
+
if (def.minimum !== undefined) r.min = def.minimum;
|
|
351
|
+
if (def.maximum !== undefined) r.max = def.maximum;
|
|
352
|
+
// exclusive* 按非严格边界处理(mm_validator 无 exclusive 语义)
|
|
353
|
+
if (def.exclusiveMinimum !== undefined && r.min === undefined) r.min = def.exclusiveMinimum;
|
|
354
|
+
if (def.exclusiveMaximum !== undefined && r.max === undefined) r.max = def.exclusiveMaximum;
|
|
355
|
+
|
|
356
|
+
const minLen = pick(def.minLength, def.minItems, def.min_length);
|
|
357
|
+
const maxLen = pick(def.maxLength, def.maxItems, def.max_length);
|
|
358
|
+
if (minLen !== undefined) r.min_length = minLen;
|
|
359
|
+
if (maxLen !== undefined) r.max_length = maxLen;
|
|
360
|
+
|
|
361
|
+
// 旧扁平格式的 min/max 别名:按运行时值类型落到数值范围或长度
|
|
362
|
+
if (def.min !== undefined) {
|
|
363
|
+
if (typeof value === 'number') { if (r.min === undefined) r.min = def.min; }
|
|
364
|
+
else if (r.min_length === undefined) r.min_length = def.min;
|
|
365
|
+
}
|
|
366
|
+
if (def.max !== undefined) {
|
|
367
|
+
if (typeof value === 'number') { if (r.max === undefined) r.max = def.max; }
|
|
368
|
+
else if (r.max_length === undefined) r.max_length = def.max;
|
|
369
|
+
}
|
|
370
|
+
return r;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** params 会跳过空串,改用 mm_validator 的单项工具补检,避免约束被静默弱化 */
|
|
374
|
+
function checkEmpty(fullPath, field, value, def, errs) {
|
|
375
|
+
const minLen = pick(def.minLength, def.minItems, def.min_length, def.min);
|
|
376
|
+
const maxLen = pick(def.maxLength, def.maxItems, def.max_length, def.max);
|
|
377
|
+
if (minLen !== undefined || maxLen !== undefined) {
|
|
378
|
+
const out = run('length', { field: field, value: value, min: minLen, max: maxLen });
|
|
379
|
+
if (out && out.errors) for (let i = 0; i < out.errors.length; i++) errs.push(fullPath + ': ' + String(out.errors[i]));
|
|
380
|
+
}
|
|
381
|
+
const en = def.enum || (def.const !== undefined ? [def.const] : null);
|
|
382
|
+
if (en) {
|
|
383
|
+
const out = run('enum', { field: field, value: value, options: en });
|
|
384
|
+
if (out && out.errors) for (let i = 0; i < out.errors.length; i++) errs.push(fullPath + ': ' + String(out.errors[i]));
|
|
385
|
+
}
|
|
386
|
+
if (def.pattern) {
|
|
387
|
+
const out = run('pattern', { field: field, value: value, pattern: def.pattern });
|
|
388
|
+
if (out && out.errors) for (let i = 0; i < out.errors.length; i++) errs.push(fullPath + ': ' + String(out.errors[i]));
|
|
389
|
+
}
|
|
390
|
+
const t = Array.isArray(def.type) ? def.type[0] : def.type;
|
|
391
|
+
if (t && t !== 'null') {
|
|
392
|
+
const out = run('type', { field: field, value: value, expected_type: t });
|
|
393
|
+
if (out && out.errors) for (let i = 0; i < out.errors.length; i++) errs.push(fullPath + ': ' + String(out.errors[i]));
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function collectParamErrors(out, prefix, errs) {
|
|
398
|
+
if (!out || !out.errors) return;
|
|
399
|
+
for (const f in out.errors) {
|
|
400
|
+
const list = out.errors[f] || [];
|
|
401
|
+
for (let i = 0; i < list.length; i++) {
|
|
402
|
+
errs.push(joinPath(prefix, f) + ': ' + String(list[i]));
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** 一层 object 的校验:字段清单比对 + 一次 params 批量调用 + 嵌套递归 */
|
|
408
|
+
function validateLevel(fields, obj, prefix, errs, noExtra) {
|
|
409
|
+
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return;
|
|
410
|
+
|
|
411
|
+
if (noExtra) {
|
|
412
|
+
for (const k in obj) {
|
|
413
|
+
if (!Object.prototype.hasOwnProperty.call(fields, k)) {
|
|
414
|
+
errs.push(joinPath(prefix, k) + ': 未在 schema 中声明(additionalProperties: false)');
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const rules = {};
|
|
420
|
+
const emptyFields = [];
|
|
421
|
+
for (const f in fields) {
|
|
422
|
+
const r = ruleOf(fields[f], obj[f]);
|
|
423
|
+
if (Object.keys(r).length) rules[f] = r;
|
|
424
|
+
if (obj[f] === '') emptyFields.push(f);
|
|
425
|
+
}
|
|
426
|
+
if (Object.keys(rules).length) {
|
|
427
|
+
collectParamErrors(run('params', { input: obj, rules: rules }), prefix, errs);
|
|
428
|
+
}
|
|
429
|
+
for (let i = 0; i < emptyFields.length; i++) {
|
|
430
|
+
const f = emptyFields[i];
|
|
431
|
+
checkEmpty(joinPath(prefix, f), f, obj[f], fields[f], errs);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
for (const f in fields) {
|
|
435
|
+
const def = fields[f];
|
|
436
|
+
const v = obj[f];
|
|
437
|
+
if (v === undefined || v === null) continue;
|
|
438
|
+
const p = joinPath(prefix, f);
|
|
439
|
+
if (def.properties && typeof v === 'object' && !Array.isArray(v)) {
|
|
440
|
+
validateLevel(childFields(def), v, p, errs, def.additionalProperties === false);
|
|
441
|
+
}
|
|
442
|
+
if (def.items && Array.isArray(v)) {
|
|
443
|
+
for (let i = 0; i < v.length; i++) {
|
|
444
|
+
const elem = v[i];
|
|
445
|
+
const ep = p + '[' + i + ']';
|
|
446
|
+
const idef = def.items;
|
|
447
|
+
if (idef.properties && elem && typeof elem === 'object' && !Array.isArray(elem)) {
|
|
448
|
+
validateLevel(childFields(idef), elem, ep, errs, idef.additionalProperties === false);
|
|
449
|
+
} else {
|
|
450
|
+
const r = ruleOf(idef, elem);
|
|
451
|
+
if (Object.keys(r).length) {
|
|
452
|
+
const out = run('params', { input: { _: elem }, rules: { _: r } });
|
|
453
|
+
if (out && out.errors && out.errors._) {
|
|
454
|
+
for (let j = 0; j < out.errors._.length; j++) {
|
|
455
|
+
errs.push(ep + ': ' + String(out.errors._[j]).replace(/^_\s*/, ''));
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
if (elem === '') checkEmpty(ep, '_', elem, idef, errs);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/** 校验数据体:规则判定全部由 mm_validator 执行,返回错误数组或 null */
|
|
467
|
+
function validate(model, body) {
|
|
468
|
+
if (!model || model.schemaless || !model.jsonSchema) return null;
|
|
469
|
+
const errs = [];
|
|
470
|
+
validateLevel(model.schema, body || {}, '', errs, model.additionalProperties === false);
|
|
471
|
+
return errs.length ? errs : null;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** 只校验、不写入 */
|
|
475
|
+
function check(model, row) {
|
|
476
|
+
const errors = validate(model, row) || [];
|
|
477
|
+
return { ok: errors.length === 0, errors: errors };
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** 当前生效的校验器信息 */
|
|
481
|
+
function validatorInfo() {
|
|
482
|
+
let version = null;
|
|
483
|
+
if (V) {
|
|
484
|
+
try { version = require(path.join(V.TOOL_DIR, '..', 'package.json')).version; } catch (e) { /* ignore */ }
|
|
485
|
+
}
|
|
486
|
+
return {
|
|
487
|
+
package: 'mm_validator',
|
|
488
|
+
version: version,
|
|
489
|
+
loaded: !!V,
|
|
490
|
+
tool_dir: V ? V.TOOL_DIR : null,
|
|
491
|
+
available_tools: V && typeof V.listTools === 'function' ? V.listTools() : [],
|
|
492
|
+
engine_tools: Object.keys(CALLS.by_tool),
|
|
493
|
+
schema_draft: DRAFT,
|
|
494
|
+
allowed_types: ALLOWED_TYPES.slice(),
|
|
495
|
+
forbidden_types: Object.keys(FORBIDDEN_TYPES),
|
|
496
|
+
calls: CALLS.total,
|
|
497
|
+
calls_by_tool: Object.assign({}, CALLS.by_tool),
|
|
498
|
+
error: V_ERROR
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** 填充 schema 默认值(default 是标准 JSON Schema 关键词) */
|
|
503
|
+
function fillDefaults(model, body) {
|
|
504
|
+
const out = {};
|
|
505
|
+
const data = body || {};
|
|
506
|
+
for (const k in data) out[k] = clone(data[k]);
|
|
507
|
+
for (const f in model.schema) {
|
|
508
|
+
const def = model.schema[f];
|
|
509
|
+
if (def.default !== undefined && out[f] === undefined) out[f] = clone(def.default);
|
|
510
|
+
}
|
|
511
|
+
return out;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/** 按 fields 投影 */
|
|
515
|
+
function project(row, fields, key) {
|
|
516
|
+
if (!fields || !fields.length) return clone(row);
|
|
517
|
+
const out = {};
|
|
518
|
+
if (key && row[key] !== undefined) out[key] = row[key];
|
|
519
|
+
for (let i = 0; i < fields.length; i++) {
|
|
520
|
+
const f = fields[i];
|
|
521
|
+
if (row[f] !== undefined) out[f] = clone(row[f]);
|
|
522
|
+
}
|
|
523
|
+
return out;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
module.exports = {
|
|
527
|
+
DRAFT: DRAFT,
|
|
528
|
+
ALLOWED_TYPES: ALLOWED_TYPES,
|
|
529
|
+
normalize: normalize,
|
|
530
|
+
normalizeSchema: normalizeSchema,
|
|
531
|
+
toStandard: toStandard,
|
|
532
|
+
setField: setField,
|
|
533
|
+
getField: getField,
|
|
534
|
+
validate: validate,
|
|
535
|
+
check: check,
|
|
536
|
+
validatorInfo: validatorInfo,
|
|
537
|
+
fillDefaults: fillDefaults,
|
|
538
|
+
project: project,
|
|
539
|
+
clone: clone
|
|
540
|
+
};
|