- 新增最外层错误中间件:body-parser 的 400/413 等也转成约定 JSON, 客户端只收通用文案,5xx 详情仅进日志 - token 校验对 user 服务非 2xx 抛错而非按未登录处理, 避免服务抖动时在线用户被负缓存 60 秒踢回登录页
90 lines
2.9 KiB
JavaScript
90 lines
2.9 KiB
JavaScript
import fetch from "node-fetch";
|
||
|
||
const USER_SERVICE_URL = process.env.USER_SERVICE_URL || "http://127.0.0.1:9010";
|
||
const CACHE_TTL = 5 * 60 * 1000; // 成功结果缓存 5 分钟
|
||
const NEGATIVE_TTL = 60 * 1000; // 无效 token 短缓存,防止打爆 user 服务
|
||
const MAX_CACHE_SIZE = 2000;
|
||
const LOOKUP_TIMEOUT = 5000; // user 服务偶发无响应时不能拖住 health 的全部请求
|
||
|
||
// key -> { user, expiresAt },Map 按插入序实现简易 LRU
|
||
const cache = new Map();
|
||
|
||
function cacheGet(key) {
|
||
const hit = cache.get(key);
|
||
if (!hit) return undefined;
|
||
if (Date.now() > hit.expiresAt) {
|
||
cache.delete(key);
|
||
return undefined;
|
||
}
|
||
// 重新插入以更新 LRU 顺序
|
||
cache.delete(key);
|
||
cache.set(key, hit);
|
||
return hit.user;
|
||
}
|
||
|
||
function cacheSet(key, user, ttl) {
|
||
cache.set(key, { user, expiresAt: Date.now() + ttl });
|
||
if (cache.size > MAX_CACHE_SIZE) {
|
||
cache.delete(cache.keys().next().value);
|
||
}
|
||
}
|
||
|
||
async function lookup(body) {
|
||
const res = await fetch(`${USER_SERVICE_URL}/user/userInfo`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify(body),
|
||
signal: AbortSignal.timeout(LOOKUP_TIMEOUT),
|
||
});
|
||
// 非 2xx 视为服务故障而不是「token 无效」:曾把 5xx 当作未登录,
|
||
// 在线用户会被负缓存 60 秒,表现为莫名被踢回登录页
|
||
if (!res.ok) {
|
||
throw new Error(`user service responded ${res.status}`);
|
||
}
|
||
const data = await res.json();
|
||
return data?.data?.user || null;
|
||
}
|
||
|
||
/**
|
||
* 仅按 token 获取用户信息(带 5 分钟进程内缓存,token→user)
|
||
*
|
||
* 注意:缓存期内登出/账户锁定/用户信息变更最多延迟 5 分钟生效
|
||
* (user 服务自身接口即时生效)
|
||
*
|
||
* 只保留 token 路径:user 服务已不再接受按 userId 明文查询,
|
||
* 故不存在 userId 兜底,避免凭 userId 冒充他人身份。
|
||
*
|
||
* @param {string} token 登录 token
|
||
* @param {Object} [options]
|
||
* @param {boolean} [options.strict] 严格模式:user 服务不可用时不返回 null,
|
||
* 而是抛出 code = USER_SERVICE_UNAVAILABLE 的错误,供接口区分「登录失效」与「服务故障」
|
||
* @returns {Promise<Object|null>} 用户信息或 null
|
||
*/
|
||
export async function getUserByToken(token, options = {}) {
|
||
if (!token) return null;
|
||
|
||
const key = `tk:${token}`;
|
||
const cached = cacheGet(key);
|
||
if (cached !== undefined) return cached;
|
||
|
||
try {
|
||
const user = await lookup({ token });
|
||
if (user) {
|
||
cacheSet(key, user, CACHE_TTL);
|
||
return user;
|
||
}
|
||
// 无效 token 短缓存,保护 user 服务
|
||
cacheSet(key, null, NEGATIVE_TTL);
|
||
} catch (err) {
|
||
// 网络异常不缓存,避免把故障期内的问题固化 5 分钟
|
||
console.error("getUserByToken error:", err.message);
|
||
if (options.strict) {
|
||
const unavailable = new Error("用户服务暂不可用");
|
||
unavailable.code = "USER_SERVICE_UNAVAILABLE";
|
||
throw unavailable;
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|