如何在TypeScript Express API中定义服务函数ID常量并校验请求值
在Express中定义服务函数ID常量及校验的实现方案
一、可用的数据类型与实现方式
1. 普通对象
最直接的实现方式,用对象存储键值对,代码直观易懂:
const FunctionIds = { LoginFunction: 0, GetOrderInfo: 101, CheckInventoryLevels: 201 };
校验时提取请求中的ID,检查是否存在于对象的值集合中:
const requestFuncId = req.body.funcId; const isValid = Object.values(FunctionIds).includes(requestFuncId);
优点是上手快、可读性强;缺点是如果需要校验ID范围(比如0-100归为登录类),需要额外编写判断逻辑。
2. TypeScript枚举
如果项目基于TypeScript开发,枚举是天生适配的方案:
enum FunctionIds { LoginFunction = 0, GetOrderInfo = 101, CheckInventoryLevels = 201 }
校验逻辑和对象类似,但TypeScript的类型系统能在开发阶段就拦截非法值,大幅降低运行时错误概率。
3. Map映射
如果需要动态增删常量,Map的灵活性更高:
const FunctionIds = new Map([ ['LoginFunction', 0], ['GetOrderInfo', 101], ['CheckInventoryLevels', 201] ]);
校验时将Map的值转为数组后判断:
const isValid = Array.from(FunctionIds.values()).includes(req.body.funcId);
4. 类的静态属性
若想把常量和校验逻辑封装在一起,可以用类的静态属性实现:
class FunctionIdConstants { static LoginFunction = 0; static GetOrderInfo = 101; static CheckInventoryLevels = 201; static isValid(id) { return Object.values(this).includes(id); } }
校验时直接调用静态方法即可:
const isValid = FunctionIdConstants.isValid(req.body.funcId);
二、更优的推荐方案
1. TypeScript枚举(优先推荐)
如果项目使用TypeScript,这是最优解:
- 开发阶段有类型提示,避免拼写错误
- 键值映射清晰,代码可读性强
- 可配合类型守卫,在编译阶段就拦截非法ID
示例代码:
enum FunctionIds { LoginFunction = 0, GetOrderInfo = 101, CheckInventoryLevels = 201 } // 自定义类型守卫,确保ID合法性 function isFunctionId(id: unknown): id is FunctionIds { return Object.values(FunctionIds).includes(id as FunctionIds); } // Express中间件中实现校验 app.use((req, res, next) => { const funcId = req.body.funcId; if (!isFunctionId(funcId)) { return res.status(400).send('非法的服务函数ID'); } next(); });
2. 带范围校验的封装对象(纯JS项目)
纯JavaScript项目中,推荐给对象添加范围校验逻辑,将同类别ID分组管理:
const FunctionIds = { // 具体常量定义 LoginFunction: 0, GetOrderInfo: 101, CheckInventoryLevels: 201, // 类别范围定义 ranges: { login: [0, 100], order: [101, 200], inventory: [201, 300] }, // 统一校验方法 isValid(id) { // 先检查是否为明确定义的常量 if (Object.values(this).includes(id)) return true; // 再检查是否在合法范围内(若允许范围内所有ID都有效) return Object.values(this.ranges).some(([min, max]) => id >= min && id <= max); } };
这种方式既支持精准匹配单个常量,也能批量校验范围,灵活性更高。
3. Set集合(快速校验场景)
如果只需要快速判断ID是否合法,不需要关联业务名称,直接用Set集合:
const VALID_FUNCTION_IDS = new Set([0, 101, 201]); // 校验时间复杂度为O(1),效率极高 const isValid = VALID_FUNCTION_IDS.has(req.body.funcId);
适合对校验性能有要求的场景。
内容的提问来源于stack exchange,提问作者whatwhatwhat
相关产品推荐
相关产品推荐

