mm_datas 0.0.0-stage → 5.3.1
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/pool.js
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 基于 mm_admin 的实例池封装
|
|
5
|
+
*
|
|
6
|
+
* 范式与 mm_dao / mm_store 一致:
|
|
7
|
+
* const pool = reg('mm_datas'); // 全局注册表里唯一的管理器池
|
|
8
|
+
* pool.setClass(DataManager); // 绑定本模块的管理数据类
|
|
9
|
+
* pool.setServer(sharedStore); // 注入共享存储(所有集合共用)
|
|
10
|
+
* pool.get('role', config) // 按名字缓存 DataManager 实例
|
|
11
|
+
*
|
|
12
|
+
* 对外主入口 dataAdmin(name, def) = pool.data(name, def) = pool.get(name, ...)
|
|
13
|
+
*/
|
|
14
|
+
const fs = require('fs');
|
|
15
|
+
const path = require('path');
|
|
16
|
+
const S = require('./store.js');
|
|
17
|
+
const B = require('./backend.js');
|
|
18
|
+
const mm = require('mm_admin');
|
|
19
|
+
const { DataManager, EXAMPLE_MODEL_DIR } = require('./manager.js');
|
|
20
|
+
|
|
21
|
+
const DEFAULT_NAMESPACE = 'mm_datas';
|
|
22
|
+
let _current = null;
|
|
23
|
+
let _resetSeq = 0;
|
|
24
|
+
|
|
25
|
+
function makeStore(config, namespace) {
|
|
26
|
+
const cfg = Object.assign({}, config || {}, { namespace: (config && config.namespace) || namespace });
|
|
27
|
+
let store;
|
|
28
|
+
if (cfg.store && typeof cfg.store === 'object' && typeof cfg.store.list === 'function') {
|
|
29
|
+
store = cfg.store; // 自定义 adapter(MySQL / Redis / S5 ...)
|
|
30
|
+
} else if (cfg.store === 'hybrid' || cfg.store === 'rowfile' || cfg.store === 'auto' ||
|
|
31
|
+
(!cfg.store && (cfg.models || cfg.dir))) {
|
|
32
|
+
// 装载了 *_model.json(或显式给了数据目录)时,默认按 v5 目录布局落盘:
|
|
33
|
+
// 静态 data/<name>/000001.json;动态 mm_cache + mm_mongodb(离线回退 _rows.json)
|
|
34
|
+
store = S.createStore('hybrid', cfg);
|
|
35
|
+
} else {
|
|
36
|
+
store = S.createStore(cfg.store || 'memory', cfg);
|
|
37
|
+
}
|
|
38
|
+
if (!store.models) store.models = new Map(); // 共享的模型定义表
|
|
39
|
+
if (!store.seq) store.seq = new Map(); // 共享的自增序列
|
|
40
|
+
return store;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 扫描模型目录:优先 *_model.json;目录里没有规范文件时兼容旧命名 */
|
|
44
|
+
function scanModelFiles(dir) {
|
|
45
|
+
const target = dir || EXAMPLE_MODEL_DIR;
|
|
46
|
+
if (!fs.existsSync(target)) return [];
|
|
47
|
+
const all = fs.readdirSync(target).filter(function (f) { return /\.json$/i.test(f); }).sort();
|
|
48
|
+
const standard = all.filter(function (f) { return /_model\.json$/i.test(f); });
|
|
49
|
+
const files = standard.length ? standard : all;
|
|
50
|
+
return files.map(function (f) {
|
|
51
|
+
return { file: f, path: path.join(target, f), name: path.basename(f, '.json').replace(/_model$/i, '') };
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function clearStore(store) {
|
|
56
|
+
if (!store) return;
|
|
57
|
+
if (store.models) store.models.clear();
|
|
58
|
+
if (store.seq) store.seq.clear();
|
|
59
|
+
if (typeof store.tableNames === 'function') {
|
|
60
|
+
const names = store.tableNames();
|
|
61
|
+
for (let i = 0; i < names.length; i++) store.clear(names[i]);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 借一个临时实例执行批量装载,避免把引导集合留在实例池里 */
|
|
66
|
+
function loadModels(pool, dir) {
|
|
67
|
+
const store = pool.getServer();
|
|
68
|
+
// 装载期间暂停自动落盘:seed 会触发 autoSave,否则引导集合会被写成一个空 .json
|
|
69
|
+
const autoSave = store.autoSave;
|
|
70
|
+
if (autoSave) store.autoSave = false;
|
|
71
|
+
try {
|
|
72
|
+
const boot = new DataManager(
|
|
73
|
+
{ name: '__bootstrap__', namespace: pool.config.namespace || DEFAULT_NAMESPACE },
|
|
74
|
+
store
|
|
75
|
+
);
|
|
76
|
+
const names = boot.loadModels(dir);
|
|
77
|
+
store.models.delete('__bootstrap__');
|
|
78
|
+
// 引导集合必须整表移除:只 clear 会留下空表,被 save() 写成 __bootstrap__.json
|
|
79
|
+
if (typeof store.dropTable === 'function') store.dropTable('__bootstrap__');
|
|
80
|
+
else if (typeof store.clear === 'function') store.clear('__bootstrap__');
|
|
81
|
+
return names;
|
|
82
|
+
} finally {
|
|
83
|
+
if (autoSave) store.autoSave = autoSave;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 按名字取集合实例;同名复用,再次传 def 则重定义 */
|
|
88
|
+
function poolData(pool, name, def) {
|
|
89
|
+
if (!name || typeof name !== 'string') {
|
|
90
|
+
throw new Error('集合名必须是非空字符串');
|
|
91
|
+
}
|
|
92
|
+
const ns = pool.config.namespace || DEFAULT_NAMESPACE;
|
|
93
|
+
const existed = pool.has(name);
|
|
94
|
+
const cfg = { namespace: ns };
|
|
95
|
+
if (def !== undefined) cfg.def = def;
|
|
96
|
+
const inst = pool.get(name, cfg);
|
|
97
|
+
if (existed && def !== undefined) inst.define(def);
|
|
98
|
+
return inst;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 创建(或取得)一个具名实例池。不同 namespace 之间数据完全隔离。
|
|
103
|
+
* @param {string} [namespace] 池名,缺省 'mm_datas'
|
|
104
|
+
* @param {object} [config] { store, dir, autoSave, persist, flush_interval, models }
|
|
105
|
+
*/
|
|
106
|
+
function createPool(namespace, config) {
|
|
107
|
+
const ns = namespace || DEFAULT_NAMESPACE;
|
|
108
|
+
const pool = mm.reg(ns);
|
|
109
|
+
if (!pool.getClass()) pool.setClass(DataManager);
|
|
110
|
+
if (!pool.getServer()) pool.setServer(makeStore(config, ns));
|
|
111
|
+
if (!pool.config.namespace) pool.setConfig({ namespace: ns });
|
|
112
|
+
if (!pool.data) {
|
|
113
|
+
pool.data = function (name, def) { return poolData(pool, name, def); };
|
|
114
|
+
}
|
|
115
|
+
// 外部访问层的显式异步入口(同步 CRUD 不依赖它们)
|
|
116
|
+
if (!pool.connect) pool.connect = async function () { return storeOf(pool).connect(); };
|
|
117
|
+
if (!pool.flush) pool.flush = async function () { return storeOf(pool).flush(); };
|
|
118
|
+
if (!pool.restore) pool.restore = async function (dir) { return storeOf(pool).restore(dir); };
|
|
119
|
+
if (!pool.backends) pool.backends = function () { return storeOf(pool).backends(); };
|
|
120
|
+
if (!pool.modelFiles) pool.modelFiles = function (dir) { return scanModelFiles((config && config.models) || dir); };
|
|
121
|
+
// 本地持久化策略:立即落盘 / 定时落盘 / 关闭收尾 / 状态查询
|
|
122
|
+
if (!pool.flushNow) pool.flushNow = function () { return flushNow(pool); };
|
|
123
|
+
if (!pool.close) pool.close = function () { return closePool(pool); };
|
|
124
|
+
if (!pool.startAutoFlush) pool.startAutoFlush = function (interval) {
|
|
125
|
+
const store = pool.getServer();
|
|
126
|
+
if (store && typeof store.startAutoFlush === 'function') store.startAutoFlush(interval);
|
|
127
|
+
return pool;
|
|
128
|
+
};
|
|
129
|
+
if (!pool.stopAutoFlush) pool.stopAutoFlush = function () {
|
|
130
|
+
const store = pool.getServer();
|
|
131
|
+
if (store && typeof store.stopAutoFlush === 'function') store.stopAutoFlush();
|
|
132
|
+
return pool;
|
|
133
|
+
};
|
|
134
|
+
if (!pool.persistStatus) pool.persistStatus = function () { return persistStatus(pool); };
|
|
135
|
+
if (config && config.models) loadModels(pool, config.models);
|
|
136
|
+
return pool;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* 立即落盘池中的脏数据
|
|
141
|
+
* @param {object} pool 实例池
|
|
142
|
+
* @returns {object} 落盘结果
|
|
143
|
+
*/
|
|
144
|
+
function flushNow(pool) {
|
|
145
|
+
const store = pool.getServer();
|
|
146
|
+
if (!store) return { ok: true, skipped: true, reason: '池未绑定 store' };
|
|
147
|
+
return typeof store.saveNow === 'function'
|
|
148
|
+
? store.saveNow()
|
|
149
|
+
: { ok: true, skipped: true, reason: '当前 store 不支持本地落盘' };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* 关闭池:停止定时落盘并保存剩余数据
|
|
154
|
+
* @param {object} pool 实例池
|
|
155
|
+
* @returns {object} 落盘结果
|
|
156
|
+
*/
|
|
157
|
+
function closePool(pool) {
|
|
158
|
+
const store = pool.getServer();
|
|
159
|
+
if (!store) return { ok: true, skipped: true, reason: '池未绑定 store' };
|
|
160
|
+
return typeof store.close === 'function' ? store.close() : flushNow(pool);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 池的持久化策略与落盘统计
|
|
165
|
+
* @param {object} pool 实例池
|
|
166
|
+
* @returns {object} 状态信息
|
|
167
|
+
*/
|
|
168
|
+
function persistStatus(pool) {
|
|
169
|
+
const store = pool.getServer();
|
|
170
|
+
if (!store) return { backend: '', persist: false, dirty: false };
|
|
171
|
+
return typeof store.persistStatus === 'function'
|
|
172
|
+
? store.persistStatus()
|
|
173
|
+
: { backend: store.constructor.name, persist: false, dirty: false };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function storeOf(pool) {
|
|
177
|
+
const s = pool.getServer();
|
|
178
|
+
if (!s || typeof s.connect !== 'function') {
|
|
179
|
+
throw new Error('当前池是纯内存 store,请用 createPool(ns, { store:"hybrid", dir, models }) 开启外部访问层');
|
|
180
|
+
}
|
|
181
|
+
return s;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function currentPool() {
|
|
185
|
+
if (!_current) _current = createPool(DEFAULT_NAMESPACE);
|
|
186
|
+
return _current;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* dataAdmin(name, def?, config?)
|
|
191
|
+
* - dataAdmin() -> 当前 mm_admin 池
|
|
192
|
+
* - dataAdmin({ ...config }) -> 新建独立池
|
|
193
|
+
* - dataAdmin('role') -> 名为 role 的 DataManager 实例(角色数据集合)
|
|
194
|
+
* - dataAdmin('role', def) -> 带 schema 定义 / 重定义
|
|
195
|
+
*/
|
|
196
|
+
function dataAdmin(name, def, config) {
|
|
197
|
+
if (name === undefined || name === null) {
|
|
198
|
+
if (config) {
|
|
199
|
+
_current = createPool(config.namespace || DEFAULT_NAMESPACE, config);
|
|
200
|
+
return _current;
|
|
201
|
+
}
|
|
202
|
+
return currentPool();
|
|
203
|
+
}
|
|
204
|
+
if (typeof name === 'object' && !Array.isArray(name)) {
|
|
205
|
+
const pool = createPool(name.namespace || name.name, name);
|
|
206
|
+
_current = pool;
|
|
207
|
+
return pool;
|
|
208
|
+
}
|
|
209
|
+
const pool = config ? createPool(config.namespace || DEFAULT_NAMESPACE, config) : currentPool();
|
|
210
|
+
return poolData(pool, name, def);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
dataAdmin.pool = function () { return currentPool(); };
|
|
214
|
+
dataAdmin.use = function (pool) { _current = pool; return pool; };
|
|
215
|
+
dataAdmin.reset = function (config) {
|
|
216
|
+
if (config && (config.store || config.dir || config.namespace)) {
|
|
217
|
+
_current = createPool(config.namespace || (DEFAULT_NAMESPACE + ':r' + (++_resetSeq)), config);
|
|
218
|
+
} else {
|
|
219
|
+
const pool = currentPool();
|
|
220
|
+
pool.clear();
|
|
221
|
+
clearStore(pool.getServer());
|
|
222
|
+
}
|
|
223
|
+
return currentPool();
|
|
224
|
+
};
|
|
225
|
+
dataAdmin.loadModels = function (dir) { return loadModels(currentPool(), dir || EXAMPLE_MODEL_DIR); };
|
|
226
|
+
dataAdmin.modelFiles = function (dir) { return scanModelFiles(dir || EXAMPLE_MODEL_DIR); };
|
|
227
|
+
dataAdmin.createPool = createPool;
|
|
228
|
+
dataAdmin.class = DataManager;
|
|
229
|
+
dataAdmin.probe = B.probe;
|
|
230
|
+
dataAdmin.connect = async function (pool) { return storeOf(pool || currentPool()).connect(); };
|
|
231
|
+
dataAdmin.flush = async function (pool) { return storeOf(pool || currentPool()).flush(); };
|
|
232
|
+
dataAdmin.flushNow = function (pool) { return flushNow(pool || currentPool()); };
|
|
233
|
+
dataAdmin.close = function (pool) { return closePool(pool || currentPool()); };
|
|
234
|
+
dataAdmin.persistStatus = function (pool) { return persistStatus(pool || currentPool()); };
|
|
235
|
+
dataAdmin.restore = async function (dir, pool) { return storeOf(pool || currentPool()).restore(dir); };
|
|
236
|
+
dataAdmin.backends = function (pool) {
|
|
237
|
+
const s = (pool || currentPool()).getServer();
|
|
238
|
+
return typeof s.backends === 'function' ? s.backends() : { backend: s.constructor.name, dependencies: B.probe() };
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* 取一个「注册表级」入口:不绑定具体集合,也不会在池里留下集合记录。
|
|
243
|
+
* 用于 verify / stats / save / load / dump / loadModels 这类全局操作。
|
|
244
|
+
*/
|
|
245
|
+
function registry(pool) {
|
|
246
|
+
const p = pool || currentPool();
|
|
247
|
+
const store = p.getServer();
|
|
248
|
+
const inst = Object.create(DataManager.prototype);
|
|
249
|
+
inst.config = {};
|
|
250
|
+
inst.name = '__registry__';
|
|
251
|
+
inst.server = store;
|
|
252
|
+
inst._store = store;
|
|
253
|
+
inst._namespace = p.config.namespace || DEFAULT_NAMESPACE;
|
|
254
|
+
return inst;
|
|
255
|
+
}
|
|
256
|
+
dataAdmin.registry = registry;
|
|
257
|
+
|
|
258
|
+
module.exports = {
|
|
259
|
+
dataAdmin: dataAdmin,
|
|
260
|
+
createPool: createPool,
|
|
261
|
+
currentPool: currentPool,
|
|
262
|
+
loadModels: loadModels,
|
|
263
|
+
scanModelFiles: scanModelFiles,
|
|
264
|
+
registry: registry,
|
|
265
|
+
flushNow: flushNow,
|
|
266
|
+
closePool: closePool,
|
|
267
|
+
persistStatus: persistStatus,
|
|
268
|
+
DataManager: DataManager,
|
|
269
|
+
EXAMPLE_MODEL_DIR: EXAMPLE_MODEL_DIR,
|
|
270
|
+
DEFAULT_NAMESPACE: DEFAULT_NAMESPACE,
|
|
271
|
+
// mm_admin 全局注册表直通
|
|
272
|
+
reg: mm.reg,
|
|
273
|
+
unreg: mm.unreg,
|
|
274
|
+
setSecret: mm.setSecret,
|
|
275
|
+
list: mm.list,
|
|
276
|
+
Admin: mm.Admin
|
|
277
|
+
};
|
package/lib/relation.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 关联引擎:写时校验 / 读时展开 / 快照冗余 / 反向查询
|
|
5
|
+
* 不使用数据库外键,一致性在应用层保证
|
|
6
|
+
*/
|
|
7
|
+
const { clone, project } = require('./model.js');
|
|
8
|
+
const { raise } = require('./errors.js');
|
|
9
|
+
|
|
10
|
+
function findRelation(model, name) {
|
|
11
|
+
const list = model.relations || [];
|
|
12
|
+
for (let i = 0; i < list.length; i++) if (list[i].name === name) return list[i];
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function normalizeWith(model, withSpec) {
|
|
17
|
+
if (!withSpec) return [];
|
|
18
|
+
const arr = Array.isArray(withSpec) ? withSpec : [withSpec];
|
|
19
|
+
const out = [];
|
|
20
|
+
for (let i = 0; i < arr.length; i++) {
|
|
21
|
+
const item = arr[i];
|
|
22
|
+
const isStr = typeof item === 'string';
|
|
23
|
+
const name = isStr ? item : (item.ref || item.name || item.as);
|
|
24
|
+
const rel = findRelation(model, name);
|
|
25
|
+
if (!rel) raise('REF_UNKNOWN', '模型 ' + model.name + ' 未声明关联 ' + name);
|
|
26
|
+
out.push({
|
|
27
|
+
rel: rel,
|
|
28
|
+
as: (!isStr && item.as) || rel.as || rel.name,
|
|
29
|
+
select: (!isStr && item.select) || rel.select || null,
|
|
30
|
+
mode: (!isStr && item.mode) || rel.mode || 'live'
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function unique(vals) {
|
|
37
|
+
const seen = new Set();
|
|
38
|
+
const out = [];
|
|
39
|
+
for (let i = 0; i < vals.length; i++) {
|
|
40
|
+
const v = vals[i];
|
|
41
|
+
if (v === undefined || v === null || seen.has(v)) continue;
|
|
42
|
+
seen.add(v);
|
|
43
|
+
out.push(v);
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function attachSelect(world, target, row, select) {
|
|
49
|
+
if (!select) return clone(row);
|
|
50
|
+
return project(row, select, target.key);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 读时展开:按关联批量取回,杜绝逐行查询(N+1)
|
|
55
|
+
* 每个关联仅一次后端调用
|
|
56
|
+
*/
|
|
57
|
+
function hydrate(world, model, rows, withSpec) {
|
|
58
|
+
const specs = normalizeWith(model, withSpec);
|
|
59
|
+
if (!specs.length) return rows.map(function (r) { return clone(r); });
|
|
60
|
+
const out = rows.map(function (r) { return clone(r); });
|
|
61
|
+
|
|
62
|
+
for (let i = 0; i < specs.length; i++) {
|
|
63
|
+
const spec = specs[i];
|
|
64
|
+
const rel = spec.rel;
|
|
65
|
+
const target = world.model(rel.model);
|
|
66
|
+
if (!target) raise('REF_UNKNOWN', '关联目标模型未注册: ' + rel.model);
|
|
67
|
+
|
|
68
|
+
if (rel.type === 'one-to-many') {
|
|
69
|
+
const via = rel.via || model.key;
|
|
70
|
+
const keys = unique(out.map(function (r) { return r[rel.local || model.key]; }));
|
|
71
|
+
if (!keys.length) { for (let j = 0; j < out.length; j++) out[j][spec.as] = []; continue; }
|
|
72
|
+
const q = {};
|
|
73
|
+
q[via] = { $in: keys };
|
|
74
|
+
const res = world._listBy(target.name, q, { limit: -1 });
|
|
75
|
+
const groups = new Map();
|
|
76
|
+
for (let k = 0; k < res.list.length; k++) {
|
|
77
|
+
const r = res.list[k];
|
|
78
|
+
const g = r[via];
|
|
79
|
+
if (!groups.has(g)) groups.set(g, []);
|
|
80
|
+
groups.get(g).push(attachSelect(world, target, r, spec.select));
|
|
81
|
+
}
|
|
82
|
+
for (let j = 0; j < out.length; j++) {
|
|
83
|
+
out[j][spec.as] = groups.get(out[j][rel.local || model.key]) || [];
|
|
84
|
+
}
|
|
85
|
+
} else {
|
|
86
|
+
const foreign = rel.foreign || target.key;
|
|
87
|
+
const keys = unique(out.map(function (r) { return r[rel.local]; }));
|
|
88
|
+
if (!keys.length) { for (let j = 0; j < out.length; j++) out[j][spec.as] = null; continue; }
|
|
89
|
+
const q = {};
|
|
90
|
+
q[foreign] = { $in: keys };
|
|
91
|
+
const res = world._listBy(target.name, q, { limit: -1 });
|
|
92
|
+
const map = new Map();
|
|
93
|
+
for (let k = 0; k < res.list.length; k++) map.set(res.list[k][foreign], res.list[k]);
|
|
94
|
+
for (let j = 0; j < out.length; j++) {
|
|
95
|
+
const hit = map.get(out[j][rel.local]);
|
|
96
|
+
out[j][spec.as] = hit ? attachSelect(world, target, hit, spec.select) : null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 写时校验:所有 ref 字段指向的记录存在 */
|
|
104
|
+
function validateRefs(world, model, body) {
|
|
105
|
+
const errs = [];
|
|
106
|
+
const schema = model.schema;
|
|
107
|
+
for (const field in schema) {
|
|
108
|
+
const ref = schema[field].ref;
|
|
109
|
+
if (!ref) continue;
|
|
110
|
+
const val = body[field];
|
|
111
|
+
if (val === undefined || val === null) continue;
|
|
112
|
+
if (ref.onMissing === 'keep' || ref.onMissing === 'null') continue;
|
|
113
|
+
let target;
|
|
114
|
+
try { target = world.model(ref.model); }
|
|
115
|
+
catch (e) { errs.push(field + ' 关联模型未注册: ' + ref.model); continue; }
|
|
116
|
+
const q = {};
|
|
117
|
+
q[ref.key || target.key] = val;
|
|
118
|
+
if (!world._existsBy(target.name, q)) {
|
|
119
|
+
errs.push(field + '=' + val + ' 在 ' + target.name + ' 中不存在');
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return errs;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 找到指向某个模型的本表字段 */
|
|
126
|
+
function localRefField(model, modelName) {
|
|
127
|
+
for (const f in model.schema) {
|
|
128
|
+
const ref = model.schema[f].ref;
|
|
129
|
+
if (ref && ref.model === modelName) return f;
|
|
130
|
+
}
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** 写时快照:把静态表字段冗余进动态记录,并钉扎配置版本 */
|
|
135
|
+
function snapshotFields(world, model, body) {
|
|
136
|
+
const out = {};
|
|
137
|
+
let pinned = null;
|
|
138
|
+
for (const field in model.schema) {
|
|
139
|
+
const spec = model.schema[field].snapshot;
|
|
140
|
+
if (!spec) continue;
|
|
141
|
+
const parts = String(spec).split('.');
|
|
142
|
+
const targetName = parts[0];
|
|
143
|
+
const targetField = parts[1];
|
|
144
|
+
const local = localRefField(model, targetName);
|
|
145
|
+
if (!local || body[local] === undefined) continue;
|
|
146
|
+
let target;
|
|
147
|
+
try { target = world.model(targetName); }
|
|
148
|
+
catch (e) { continue; }
|
|
149
|
+
const q = {};
|
|
150
|
+
q[target.key] = body[local];
|
|
151
|
+
const row = world._getBy(target.name, q);
|
|
152
|
+
if (row && row[targetField] !== undefined) out[field] = clone(row[targetField]);
|
|
153
|
+
if (target.readonly && target.version) pinned = target.version;
|
|
154
|
+
}
|
|
155
|
+
if (pinned && model.schema.cfg_ver) out.cfg_ver = pinned;
|
|
156
|
+
return out;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** 反查:从静态项查所有引用它的动态记录 */
|
|
160
|
+
function reverse(world, opts) {
|
|
161
|
+
opts = opts || {};
|
|
162
|
+
const refModel = world.model(opts.ref);
|
|
163
|
+
const q = {};
|
|
164
|
+
q[opts.via] = opts.key;
|
|
165
|
+
return world._listBy(refModel.name, q, opts.options || { limit: 100 });
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
module.exports = {
|
|
169
|
+
findRelation: findRelation,
|
|
170
|
+
normalizeWith: normalizeWith,
|
|
171
|
+
hydrate: hydrate,
|
|
172
|
+
validateRefs: validateRefs,
|
|
173
|
+
snapshotFields: snapshotFields,
|
|
174
|
+
reverse: reverse
|
|
175
|
+
};
|