liufumingren bd2363bf00 chore: 初始化仓库(backend / frontend / extension 三块)
- backend/:Egg 3 纯 JSON 接口服务(MySQL 8 + Redis),全部走 header 令牌鉴权;
  已彻底去掉服务端渲染(删除 page 控制器 / app/view / nunjucks / session / CSRF),
  开发时把页面请求反代到前端 dev server,生产托管 frontend/dist(SPA 回退)。
  单测 91 个通过(不需要本机数据库)。
- frontend/:Vite + Vue3 + TypeScript 的 SPA(登录 / 注册 / 找回密码 / 扫码登录与确认 /
  首页统计 / 设备管理 / 扫码记录 / 个人中心 / 测试页),vue-tsc 类型检查与构建通过。
- extension/:MV3 浏览器扩展(零构建),注入第三方 WMS 页面识别运单号并打开溯源页。
- 忽略规则统一放根 .gitignore:node_modules、dist、logs / logs-*、run、typings、
  .env*、config.local.js(含本机数据库与 Redis 密码,绝不入库)。
2026-10-17 08:50:32 +08:00

88 lines
2.4 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 { Service } = require('egg');
class CacheService extends Service {
get redis() {
return this.app.redis;
}
get prefix() {
return this.config.cache.prefix;
}
/** 统一拼 key,避免不同业务互相覆盖 */
key(name) {
return this.prefix ? `${this.prefix}${name}` : name;
}
/**
* Redis 不可用时降级(返回 fallback),不阻塞主流程:
* 缓存只是旁路,读不到就回源,写不进去也只是少一次缓存
*/
async _call(action, fallback) {
if (!this.app.redis) return fallback;
try {
return await action();
} catch (err) {
this.ctx.logger.warn('[cache] redis 异常,已降级: %s', err.message);
return fallback;
}
}
/** 读取并自动 JSON 反序列化,未命中返回 null */
async get(name) {
const raw = await this._call(() => this.redis.get(this.key(name)), null);
if (raw === null || raw === undefined) return null;
try {
return JSON.parse(raw);
} catch (err) {
// 不是 JSON 就按字符串返回
return raw;
}
}
/** 写入,ttl 单位秒;ttl <= 0 表示永不过期 */
async set(name, value, ttl = this.config.cache.ttl) {
const raw = typeof value === 'string' ? value : JSON.stringify(value);
const key = this.key(name);
if (ttl > 0) return this._call(() => this.redis.setex(key, ttl, raw), 'OK');
return this._call(() => this.redis.set(key, raw), 'OK');
}
async del(name) {
return this._call(() => this.redis.del(this.key(name)), 0);
}
async ttl(name) {
return this._call(() => this.redis.ttl(this.key(name)), -2);
}
/** 计数器,可用于限流、统计等场景(Redis 不可用时抛出,不做降级) */
async incr(name, ttl) {
const key = this.key(name);
const value = await this.redis.incr(key);
if (ttl > 0 && value === 1) {
await this.redis.expire(key, ttl);
}
return value;
}
/**
* 缓存旁路(cache-aside):命中直接返回,未命中回源并写入缓存
* loader 返回 null/undefined 时不写缓存
*/
async remember(name, ttl, loader) {
const cached = await this.get(name);
if (cached !== null) return cached;
const value = await loader();
if (value === null || value === undefined) return value;
await this.set(name, value, ttl);
return value;
}
}
module.exports = CacheService;