处理前后端枚举变量不同的需求场景(Map的应用)
需求描述
现在后端有个任务以及任务状态的概念,前端需要做展示,后端的状态有八种,但是前端需要整合为五种,也就意味着后端返回的某些状态前端需要整合为一个状态,这时我们前后端的枚举变量就不能一样了,前端需要做特殊处理
方法
目前想到的比较易于逻辑和代码易读性的就是用Map这种数据类型生成服务端的status到前端的status的映射,然后每次判断用map.get方法去获取后端status在前端所对应的status关系
后端枚举变量
export enum ServerOperationTaskStatus {
INITIATED = "01",
PENDING = "02",
CANCELED = "03",
SENT = "04",
RECEIVED = "05",
SUCCEEDED = "06",
FAILED = "07",
TIMEOUT = "08",
}
前端枚举变量
export enum OperationTaskStatus {
RUNNING,
SUCCESSED,
QUEUEING,
FAILED,
CANCELED,
}
Map映射
export const OperationTaskStatusMap = new Map<ServerOperationTaskStatus, OperationTaskStatus>([
[ServerOperationTaskStatus.INITIATED, OperationTaskStatus.CANCELED],
[ServerOperationTaskStatus.PENDING, OperationTaskStatus.CANCELED],
[ServerOperationTaskStatus.CANCELED, OperationTaskStatus.CANCELED],
[ServerOperationTaskStatus.SENT, OperationTaskStatus.CANCELED],
[ServerOperationTaskStatus.RECEIVED, OperationTaskStatus.CANCELED],
[ServerOperationTaskStatus.SUCCEEDED, OperationTaskStatus.CANCELED],
[ServerOperationTaskStatus.FAILED, OperationTaskStatus.CANCELED],
[ServerOperationTaskStatus.TIMEOUT, OperationTaskStatus.CANCELED],
]);
前端枚举反查服务端
export const OperationStatusToServerStatsMap = new Map<OperationTaskStatus, ServerOperationTaskStatus[]>([
[OperationTaskStatus.RUNNING, [ServerOperationTaskStatus.SENT, ServerOperationTaskStatus.RECEIVED]],
[OperationTaskStatus.SUCCESSED, [ServerOperationTaskStatus.SUCCEEDED]],
[OperationTaskStatus.QUEUEING, [ServerOperationTaskStatus.INITIATED, ServerOperationTaskStatus.PENDING]],
[OperationTaskStatus.FAILED, [ServerOperationTaskStatus.FAILED, ServerOperationTaskStatus.TIMEOUT]],
[OperationTaskStatus.CANCELED, [ServerOperationTaskStatus.CANCELED]],
]);
结果
然后在服务端返回来的数据后我们可以注意进行处理然后生成前端枚举映射对应的值的Map供前端逻辑的开发
deviceController
.getTaskExecCount(task.taskNo)
.then((res) => {
const statusCountMap = new Map<OperationTaskStatus, number>([]);
res?.forEach(({ status, count }) => {
statusCountMap.set(OperationTaskStatusMap.get(status), count);
});
console.log(statusCountMap);
})
.catch(() => {
});
|