WMS_MAIN/app/lib/warehouse_shard_guard.js
2026-04-17 19:21:57 +08:00

94 lines
2.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const MAX_DECIMAL_DIGITS = 20;
/**
* 将分表用的仓库 ID 规范为纯十进制数字串(与 wms_store.id / BIGINT 一致)。
* @param {*} value 待规范化的仓库 ID。
* @return {string} 规范化后的仓库 ID 字符串。
*/
function normalizeWarehouseShardId(value) {
if (value === null || value === undefined || value === '') {
throw new Error('warehouse_id 不能为空');
}
if (typeof value === 'object') {
throw new Error('warehouse_id 必须为数字');
}
const s = String(value).trim();
if (!/^\d+$/.test(s)) {
throw new Error('warehouse_id 必须为数字');
}
if (s === '0') {
throw new Error('warehouse_id 非法');
}
if (s.length > MAX_DECIMAL_DIGITS) {
throw new Error('warehouse_id 超出范围');
}
return s;
}
/**
* 校验 wms_store 中存在对应 ID 且主体为仓库(project = warehouse)。
* @param {import('egg').Application} app 应用实例。
* @param {string} warehouseIdStr normalizeWarehouseShardId 的返回值。
* @return {Promise<void>}
*/
async function assertWarehouseStoreSubject(app, warehouseIdStr) {
if (!app.model || !app.model.Store) {
return;
}
const row = await app.model.Store.findOne({
where: {
id: warehouseIdStr,
project: 'warehouse',
},
attributes: [ 'id' ],
paranoid: true,
});
if (!row) {
throw new Error(`仓库主体不存在或非仓库类型(wms_store.project 须为 warehouse): ${warehouseIdStr}`);
}
}
function validatedSetFor(app) {
if (!app._shardWarehouseIdsValidated) {
app._shardWarehouseIdsValidated = new Set();
}
return app._shardWarehouseIdsValidated;
}
/**
* 规范化并校验仓库分表 ID。
* @param {import('egg').Application} app 应用实例。
* @param {*} raw 原始仓库 ID。
* @return {Promise<string>} 规范化并校验后的仓库 ID 字符串。
*/
async function ensureShardWarehouseId(app, raw) {
const idStr = normalizeWarehouseShardId(raw);
const validatedSet = validatedSetFor(app);
if (validatedSet.has(idStr)) {
return idStr;
}
await assertWarehouseStoreSubject(app, idStr);
validatedSet.add(idStr);
return idStr;
}
/**
* 清理进程内「已校验仓库主体」缓存(例如单测或手动 clear 动态模型缓存时)。
* @param {import('egg').Application} app 应用实例。
* @return {void}
*/
function clearShardWarehouseValidationCache(app) {
if (app && app._shardWarehouseIdsValidated) {
app._shardWarehouseIdsValidated.clear();
}
}
module.exports = {
normalizeWarehouseShardId,
assertWarehouseStoreSubject,
ensureShardWarehouseId,
clearShardWarehouseValidationCache,
};