safety-eval-service-frontend/src/api/enterpriseInfo/idUtil.js

58 lines
1.4 KiB
JavaScript
Raw Normal View History

2026-06-25 16:30:37 +08:00
/**
* 雪花 ID 全局处理禁止 Number()统一字符串传递
* JS Number.MAX_SAFE_INTEGER = 9007199254740991雪花 id 超出后会精度丢失
*/
export function asId(value) {
if (value == null || value === "") {
return undefined;
}
return String(value);
}
/** 是否像主键/外键字段名 */
export function isIdFieldName(key) {
return key === "id" || key.endsWith("Id");
}
/** 对象内所有 *Id / id 字段转字符串 */
export function withIds(obj = {}) {
if (!obj || typeof obj !== "object") {
return obj;
}
const next = { ...obj };
Object.keys(next).forEach((key) => {
if (isIdFieldName(key) && next[key] != null && next[key] !== "") {
next[key] = asId(next[key]);
}
});
return next;
}
/** 分页/查询参数中的 id 字段转字符串 */
export function normalizeQueryIds(query = {}) {
const next = { ...query };
Object.keys(next).forEach((key) => {
if (isIdFieldName(key) && next[key] != null && next[key] !== "") {
next[key] = asId(next[key]);
}
});
return next;
}
/** 兼容历史 Number() 精度丢失:比较雪花 id 前 16 位 */
export function sameId(a, b) {
const sa = asId(a);
const sb = asId(b);
if (!sa || !sb) {
return false;
}
if (sa === sb) {
return true;
}
return sa.slice(0, 16) === sb.slice(0, 16);
}
/** @deprecated 使用 sameId */
export const sameDeptId = sameId;