133 lines
4.1 KiB
JavaScript
133 lines
4.1 KiB
JavaScript
const Service = require('egg').Service;
|
||
const crypto = require('crypto');
|
||
|
||
class BaseService extends Service {
|
||
constructor(ctx) {
|
||
super(ctx);
|
||
this.defaultResponse = {
|
||
isBack: true, // 是否需要返回数据
|
||
method: '', // 方法名
|
||
data: null, // 返回的数据
|
||
message: '', // 返回的消息
|
||
};
|
||
}
|
||
|
||
// 快速封装返回数据
|
||
successResponse(method, data, message = '操作成功') {
|
||
return {
|
||
...this.defaultResponse,
|
||
method,
|
||
data,
|
||
message,
|
||
};
|
||
}
|
||
|
||
errorResponse(method, message = '操作失败') {
|
||
return {
|
||
...this.defaultResponse,
|
||
method,
|
||
isBack: false,
|
||
message,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 生成唯一连接ID(优化版)
|
||
* @param {string} prefix - ID前缀,默认 'conn'
|
||
* @param {number} length - 随机部分长度,默认 8
|
||
* @param {number} maxRetries - 最大重试次数,默认 10
|
||
* @returns {Promise<string>} 唯一的ID
|
||
*/
|
||
async generateUniqueId(prefix = 'conn', length = 8, maxRetries = 10) {
|
||
const { app } = this;
|
||
let retryCount = 0;
|
||
|
||
while (retryCount < maxRetries) {
|
||
// 生成随机ID
|
||
const randomPart = crypto.randomBytes(length).toString('hex');
|
||
const uniqueId = `${prefix}:${randomPart}`;
|
||
|
||
// 检查是否已存在
|
||
const exists = await app.redis.exists(uniqueId);
|
||
|
||
if (!exists) {
|
||
// 找到唯一ID,返回
|
||
return uniqueId;
|
||
}
|
||
|
||
retryCount++;
|
||
this.logger.warn(`ID冲突,重试第${retryCount}次: ${uniqueId}`);
|
||
}
|
||
|
||
// 如果重试多次仍然冲突,使用终极方案:增加长度并添加时间戳
|
||
const finalId = `${prefix}:${Date.now().toString(36)}:${crypto.randomBytes(length + 4).toString('hex')}`;
|
||
|
||
// 最后一次检查
|
||
const exists = await app.redis.exists(finalId);
|
||
if (exists) {
|
||
throw new Error(`无法生成唯一ID,已重试${maxRetries}次`);
|
||
}
|
||
|
||
return finalId;
|
||
}
|
||
/*
|
||
* 打印结果处理
|
||
* @param {Object} data - 打印结果数据
|
||
* 数据结构示例:
|
||
* { printId: '123456', status: 'success' | 'error', message: '原始消息内容' }
|
||
* 无返回值,直接处理打印结果,例如更新数据库状态、记录日志等
|
||
*
|
||
*
|
||
*/
|
||
async printResult(data) {
|
||
const { app } = this;
|
||
const {ctx} = this;
|
||
const {printId, status, message} = data;
|
||
const { print_computer_info } = ctx;
|
||
const { uniqueId,code, printer, warehouse, computerId } = print_computer_info;
|
||
try {
|
||
//查找打印记录
|
||
const printRecord = await app.mysql.get("wms").get('wms_print_record', { id:printId });
|
||
if(!printRecord){
|
||
this.logger.warn(`未找到打印记录: ${printId}`);
|
||
return;
|
||
}
|
||
//log 是数据库json字段,存储打印日志数组,每次打印结果更新时追加日志
|
||
const logEntry = {
|
||
status,
|
||
message,
|
||
timestamp: Date.now(),
|
||
};
|
||
const printLogs = printRecord.log || [];
|
||
printLogs.push(logEntry);
|
||
//更新打印记录状态和日志
|
||
await app.mysql.get("wms").update('wms_print_record', { id:printId }, { status, log: printLogs });
|
||
console.log("打印记录printRecord",printRecord);
|
||
} catch (error) {
|
||
this.logger.error(`处理打印结果失败: ${error.message}`);
|
||
}
|
||
}
|
||
/*
|
||
* 打印机状态变更处理
|
||
* @param {Object} data - 打印机状态数据
|
||
* 数据结构示例:
|
||
* [{ name: 'printer1' }]
|
||
* 无返回值,直接处理状态变更,更新缓存状态、记录日志等
|
||
*/
|
||
async printerList(data){
|
||
const { app } = this;
|
||
const {ctx} = this;
|
||
const { print_computer_info } = ctx;
|
||
const { uniqueId,code, printer, warehouse, computerId } = print_computer_info;
|
||
try {
|
||
const printerKey = `printer:${computerId}:printerList`;
|
||
const keyData = JSON.stringify({data, updatedAt: Date.now()});
|
||
console.log(`打印机列表更新成功: `,JSON.stringify(keyData));
|
||
await app.redis.set(printerKey, keyData);
|
||
} catch (error) {
|
||
console.error(`打印机列表更新失败: ${error.message}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = BaseService; |