Initial commit: services.printer project
This commit is contained in:
commit
0f78e82c44
1
.eslintignore
Normal file
1
.eslintignore
Normal file
@ -0,0 +1 @@
|
|||||||
|
coverage
|
||||||
15
.gitignore
vendored
Normal file
15
.gitignore
vendored
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
logs/
|
||||||
|
npm-debug.log
|
||||||
|
yarn-error.log
|
||||||
|
node_modules/
|
||||||
|
*-lock.json
|
||||||
|
*-lock.yaml
|
||||||
|
yarn.lock
|
||||||
|
coverage/
|
||||||
|
.idea/
|
||||||
|
run/
|
||||||
|
.DS_Store
|
||||||
|
*.sw*
|
||||||
|
*.un~
|
||||||
|
typings/
|
||||||
|
.nyc_output/
|
||||||
36
.vscode/launch.json
vendored
Normal file
36
.vscode/launch.json
vendored
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
{
|
||||||
|
// Use IntelliSense to learn about possible attributes.
|
||||||
|
// Hover to view descriptions of existing attributes.
|
||||||
|
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"type": "node",
|
||||||
|
"request": "launch",
|
||||||
|
"name": "Egg Debug",
|
||||||
|
"runtimeExecutable": "npm",
|
||||||
|
"runtimeArgs": [
|
||||||
|
"run",
|
||||||
|
"dev",
|
||||||
|
"--",
|
||||||
|
"--inspect-brk"
|
||||||
|
],
|
||||||
|
"console": "integratedTerminal",
|
||||||
|
"restart": true,
|
||||||
|
"autoAttachChildProcesses": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "node",
|
||||||
|
"request": "launch",
|
||||||
|
"name": "Egg Test",
|
||||||
|
"runtimeExecutable": "npm",
|
||||||
|
"runtimeArgs": [
|
||||||
|
"run",
|
||||||
|
"test:local",
|
||||||
|
"--",
|
||||||
|
"--inspect-brk"
|
||||||
|
],
|
||||||
|
"autoAttachChildProcesses": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
31
README.md
Normal file
31
README.md
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
# services.printer
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## QuickStart
|
||||||
|
|
||||||
|
<!-- add docs here for user -->
|
||||||
|
|
||||||
|
see [egg docs][egg] for more detail.
|
||||||
|
|
||||||
|
### Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm i
|
||||||
|
npm run dev
|
||||||
|
open http://localhost:7001/
|
||||||
|
```
|
||||||
|
|
||||||
|
### Deploy
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm start
|
||||||
|
npm stop
|
||||||
|
```
|
||||||
|
|
||||||
|
### npm scripts
|
||||||
|
|
||||||
|
- Use `npm run lint` to check code style.
|
||||||
|
- Use `npm test` to run unit test.
|
||||||
|
|
||||||
|
[egg]: https://eggjs.org
|
||||||
69
app/controller/auth.js
Normal file
69
app/controller/auth.js
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
const Controller = require('egg').Controller;
|
||||||
|
|
||||||
|
class AuthController extends Controller {
|
||||||
|
async bind() {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
const { roomId, code, printer, warehouse, computerId } = ctx.request.body;
|
||||||
|
console.log('Received bind request with parameters:', { roomId, code, printer, warehouse, computerId });
|
||||||
|
if (!roomId || !code || !printer || !warehouse || !computerId) {
|
||||||
|
ctx.body = {
|
||||||
|
status: 'fail',
|
||||||
|
message: '缺少必要参数: roomId, code, printer, warehouse, computerId',
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 检查房间是否在线
|
||||||
|
const roomData = await app.redis.get(roomId);
|
||||||
|
if (!roomData) {
|
||||||
|
ctx.body = {
|
||||||
|
status: 'fail',
|
||||||
|
message: '房间不在线',
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成 JWT 和刷新令牌
|
||||||
|
const jwtToken = app.jwt.sign({ code, printer, warehouse, computerId }, app.config.jwt.secret, {
|
||||||
|
expiresIn: '1h',
|
||||||
|
});
|
||||||
|
const refreshToken = app.jwt.sign({ code, printer, warehouse, computerId }, app.config.jwt.secret, {
|
||||||
|
expiresIn: '100years',
|
||||||
|
});
|
||||||
|
console.log('发送消息到room:', roomId, { jwtToken, refreshToken });
|
||||||
|
if (app.ws.getRooms) {
|
||||||
|
const rooms = await app.ws.getRooms();
|
||||||
|
console.log('所有活跃房间:', rooms);
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenExpireTime = Date.now() + 3600 * 1000; // 1 hour
|
||||||
|
const res = await app.ws.sendTo(roomId, JSON.stringify({ data: { jwtToken, refreshToken, tokenExpireTime }, method: 'bind.tokenInfo' }));
|
||||||
|
console.log('消息发送结果:', res);
|
||||||
|
|
||||||
|
// 判断消息是否发送成功
|
||||||
|
if (res !== 1) {
|
||||||
|
ctx.body = {
|
||||||
|
status: 'fail',
|
||||||
|
message: '房间不在线',
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 下发令牌
|
||||||
|
ctx.body = {
|
||||||
|
message: '令牌生成成功',
|
||||||
|
jwtToken,
|
||||||
|
refreshToken,
|
||||||
|
status: 'success',
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
ctx.body = {
|
||||||
|
status: 'fail',
|
||||||
|
message: `绑定失败: ${error.message}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = AuthController;
|
||||||
59
app/controller/home.js
Normal file
59
app/controller/home.js
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
const { Controller } = require('egg');
|
||||||
|
|
||||||
|
class HomeController extends Controller {
|
||||||
|
async index() {
|
||||||
|
const { ctx } = this;
|
||||||
|
ctx.body = 'hi, egg';
|
||||||
|
}
|
||||||
|
async sendToRoom() {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
const { warehouse, computerId, method, data } = ctx.request.body; // 从 POST 请求中获取参数
|
||||||
|
const message = `当前时间: ${new Date().toLocaleString()}`;
|
||||||
|
|
||||||
|
if (!warehouse || !computerId || !method || !data) {
|
||||||
|
ctx.body = {
|
||||||
|
status: 'fail',
|
||||||
|
message: '缺少必要参数: warehouse, computerId, method, 或 data',
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const computerInfoKey = `warehouse:${warehouse}:printer:${computerId}`;
|
||||||
|
const computerInfo = await app.redis.get(computerInfoKey);
|
||||||
|
if (!computerInfo) {
|
||||||
|
ctx.body = {
|
||||||
|
status: 'fail',
|
||||||
|
message: '未找到打印机信息,无法发送消息',
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { uniqueId } = JSON.parse(computerInfo);
|
||||||
|
const roomId = uniqueId;
|
||||||
|
console.log(`准备发送消息到房间 ${roomId},消息内容: ${message} ${data} ${method}`);
|
||||||
|
try {
|
||||||
|
const res = await app.ws.sendTo(roomId, JSON.stringify({ data, method }));
|
||||||
|
if(res !== 1) {
|
||||||
|
ctx.body = {
|
||||||
|
status: 'fail',
|
||||||
|
message: '打印电脑不在线,消息发送失败,请确保打印电脑已连接并在线',
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log('消息发送结果:', res);
|
||||||
|
ctx.body = {
|
||||||
|
status: 'success',
|
||||||
|
message: '消息发送成功',
|
||||||
|
result: res,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error('发送消息时发生错误:', error);
|
||||||
|
ctx.body = {
|
||||||
|
status: 'fail',
|
||||||
|
message: '消息发送失败',
|
||||||
|
error: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = HomeController;
|
||||||
159
app/controller/print.js
Normal file
159
app/controller/print.js
Normal file
@ -0,0 +1,159 @@
|
|||||||
|
const { Controller } = require('egg');
|
||||||
|
|
||||||
|
class PrintController extends Controller {
|
||||||
|
async ws() {
|
||||||
|
const { ctx, app, logger } = this;
|
||||||
|
if (!ctx.websocket) {
|
||||||
|
throw new Error('非法请求');
|
||||||
|
}
|
||||||
|
|
||||||
|
const ws = ctx.websocket;
|
||||||
|
console.log('WebSocket 客户端已连接');
|
||||||
|
|
||||||
|
// 生成唯一ID
|
||||||
|
const uniqueId = await this.service.base.generateUniqueId();
|
||||||
|
ctx.uniqueId = uniqueId;
|
||||||
|
|
||||||
|
// 加入房间
|
||||||
|
ctx.websocket.room.join(uniqueId);
|
||||||
|
|
||||||
|
// 将房间 uniqueId 写入 Redis,有效期 300 秒
|
||||||
|
await app.redis.set(uniqueId, JSON.stringify({
|
||||||
|
connected: true,
|
||||||
|
createdAt: Date.now(),
|
||||||
|
}), 'EX', 300);
|
||||||
|
console.log(`房间 uniqueId 已写入 Redis: ${uniqueId}`);
|
||||||
|
|
||||||
|
// ✅ 1. 先声明并启动定时器
|
||||||
|
const heartbeatTimer = setInterval(async () => {
|
||||||
|
try {
|
||||||
|
// 检查连接是否还在
|
||||||
|
if (ws.readyState !== 1) { // 1 = OPEN
|
||||||
|
logger.info(`连接 ${uniqueId} 已关闭,停止心跳`);
|
||||||
|
clearInterval(heartbeatTimer);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 刷新主 key 过期时间
|
||||||
|
await app.redis.expire(uniqueId, 300);
|
||||||
|
logger.info(`刷新过期时间成功,uniqueId: ${uniqueId}`);
|
||||||
|
|
||||||
|
// 如果有打印机信息,刷新仓库打印机 key
|
||||||
|
if (ctx.print_computer_info) {
|
||||||
|
const warehouseKey = `warehouse:${ctx.print_computer_info.warehouse}:printer:${ctx.print_computer_info.computerId}`;
|
||||||
|
await app.redis.expire(warehouseKey, 300);
|
||||||
|
logger.info(`刷新仓库打印机过期时间: ${warehouseKey}`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`心跳更新失败,uniqueId: ${uniqueId}`, error);
|
||||||
|
}
|
||||||
|
}, 60000); // 60秒执行一次
|
||||||
|
|
||||||
|
// ✅ 2. 将定时器存储在多个地方,确保能正确清理
|
||||||
|
ctx.state = ctx.state || {};
|
||||||
|
ctx.state.heartbeatTimer = heartbeatTimer;
|
||||||
|
|
||||||
|
// 也存储到 ws 对象上,方便在 close 中访问
|
||||||
|
ws.heartbeatTimer = heartbeatTimer;
|
||||||
|
|
||||||
|
// 消息处理
|
||||||
|
ws.on('message', async msg => {
|
||||||
|
|
||||||
|
if(msg=="ping"){
|
||||||
|
ws.send("pong");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// method过滤
|
||||||
|
const method_filter = ['test.ping'];
|
||||||
|
if (method_filter.some(method => msg.includes(method))) {
|
||||||
|
// 过滤掉的方法不做处理
|
||||||
|
} else {
|
||||||
|
console.log('[收到消息]:', msg);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(msg);
|
||||||
|
const servicePath = data.method;
|
||||||
|
const classs = servicePath.split('.');
|
||||||
|
let systemMethods = ctx.service;
|
||||||
|
|
||||||
|
// 动态解析服务路径
|
||||||
|
for (let i = 0; i < classs.length - 1; i++) {
|
||||||
|
const className = classs[i];
|
||||||
|
if (!systemMethods[className]) {
|
||||||
|
throw new Error(`服务路径 ${className} 不存在`);
|
||||||
|
}
|
||||||
|
systemMethods = systemMethods[className];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查方法是否存在
|
||||||
|
const methodName = classs.pop();
|
||||||
|
if (typeof systemMethods[methodName] !== 'function') {
|
||||||
|
throw new Error(`方法 ${methodName} 不存在于服务 ${servicePath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 调用服务方法
|
||||||
|
const result = await systemMethods[methodName](data.data);
|
||||||
|
if (result && result.isBack === false) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`服务调用成功: ${data.method}`, result);
|
||||||
|
ws.send(JSON.stringify({
|
||||||
|
type: 'response',
|
||||||
|
method: result?.method || data.method,
|
||||||
|
data: result?.data,
|
||||||
|
message: result?.message || '服务调用成功',
|
||||||
|
}));
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`服务调用失败: ${e.message}`, e);
|
||||||
|
ws.send(JSON.stringify({
|
||||||
|
type: 'error',
|
||||||
|
message: '服务调用失败',
|
||||||
|
error: e.message,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 连接关闭 - 清理定时器
|
||||||
|
ws.on('close', async (code, reason) => {
|
||||||
|
console.log('连接关闭', code, reason);
|
||||||
|
|
||||||
|
// ✅ 3. 清理定时器
|
||||||
|
if (ws.heartbeatTimer) {
|
||||||
|
clearInterval(ws.heartbeatTimer);
|
||||||
|
console.log(`心跳定时器已清理: ${uniqueId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从 Redis 中删除 uniqueId
|
||||||
|
await app.redis.del(uniqueId);
|
||||||
|
if (ctx.print_computer_info){
|
||||||
|
const warehouseKey = `warehouse:${ctx.print_computer_info.warehouse}:printer:${ctx.print_computer_info.computerId}`;
|
||||||
|
await app.redis.del(warehouseKey);
|
||||||
|
console.log(`仓库打印机 key 已从 Redis 删除: ${warehouseKey}`);
|
||||||
|
}
|
||||||
|
console.log(`房间 uniqueId 已从 Redis 删除: ${uniqueId}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 错误处理
|
||||||
|
ws.on('error', async (error) => {
|
||||||
|
console.error('WebSocket 错误:', error);
|
||||||
|
|
||||||
|
// ✅ 4. 清理定时器
|
||||||
|
if (ws.heartbeatTimer) {
|
||||||
|
clearInterval(ws.heartbeatTimer);
|
||||||
|
console.log(`心跳定时器已清理: ${uniqueId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从 Redis 中删除 uniqueId
|
||||||
|
await app.redis.del(uniqueId);
|
||||||
|
if (ctx.print_computer_info){
|
||||||
|
const warehouseKey = `warehouse:${ctx.print_computer_info.warehouse}:printer:${ctx.print_computer_info.computerId}`;
|
||||||
|
await app.redis.del(warehouseKey);
|
||||||
|
console.log(`仓库打印机 key 已从 Redis 删除: ${warehouseKey}`);
|
||||||
|
}
|
||||||
|
console.log(`房间 uniqueId 已从 Redis 删除: ${uniqueId}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = PrintController;
|
||||||
13
app/controller/redisTest.js
Normal file
13
app/controller/redisTest.js
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
const Controller = require('egg').Controller;
|
||||||
|
|
||||||
|
class RedisTestController extends Controller {
|
||||||
|
async index() {
|
||||||
|
const { app } = this;
|
||||||
|
// 测试 Redis 连接
|
||||||
|
const result = await app.redis.set('test_key', 'Hello, Redis!');
|
||||||
|
const value = await app.redis.get('test_key');
|
||||||
|
this.ctx.body = `Redis 测试成功,值为:${value}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = RedisTestController;
|
||||||
16
app/middleware/jwtAuth.js
Normal file
16
app/middleware/jwtAuth.js
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
module.exports = (options, app) => {
|
||||||
|
return async function jwtAuth(ctx, next) {
|
||||||
|
const token = ctx.request.header.authorization;
|
||||||
|
if (!token) {
|
||||||
|
ctx.throw(401, '未登录,无法访问');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
// 验证 token
|
||||||
|
const decoded = app.jwt.verify(token, options.secret);
|
||||||
|
ctx.state.user = decoded;
|
||||||
|
await next();
|
||||||
|
} catch (err) {
|
||||||
|
ctx.throw(401, '无效的token');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
10
app/router.js
Normal file
10
app/router.js
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
/**
|
||||||
|
* @param {Egg.Application} app - egg application
|
||||||
|
*/
|
||||||
|
module.exports = app => {
|
||||||
|
const { router, controller } = app;
|
||||||
|
router.get('/', controller.home.index);
|
||||||
|
router.post('/auth/bind', controller.auth.bind);
|
||||||
|
router.post('/sendToRoom', controller.home.sendToRoom);
|
||||||
|
app.ws.route('/ws', controller.print.ws);
|
||||||
|
};
|
||||||
53
app/service/auth.js
Normal file
53
app/service/auth.js
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
const BaseService = require('./base');
|
||||||
|
|
||||||
|
class AuthService extends BaseService {
|
||||||
|
async getInfo(token) {
|
||||||
|
console.log('AuthService.getInfo called with token:', token);
|
||||||
|
const { app } = this;
|
||||||
|
try {
|
||||||
|
// 验证 JWT Token
|
||||||
|
const decoded = app.jwt.verify(token, app.config.jwt.secret);
|
||||||
|
const { computerId, warehouse } = decoded;
|
||||||
|
const uniqueId = this.ctx.uniqueId;
|
||||||
|
const data = decoded;
|
||||||
|
data.uniqueId = uniqueId;
|
||||||
|
this.ctx.print_computer_info = data;
|
||||||
|
const key = `warehouse:${warehouse}:printer:${computerId}`;
|
||||||
|
const computerInfo = await this.app.mysql.get("wms").get('wms_print_computer', {
|
||||||
|
warehouse_id: warehouse,
|
||||||
|
id: computerId
|
||||||
|
});
|
||||||
|
if(computerInfo.status==0) {
|
||||||
|
//更新数据库为激活状态
|
||||||
|
await this.app.mysql.get("wms").update('wms_print_computer', { status: 1 }, { where: { warehouse_id: warehouse, id: computerId } });
|
||||||
|
}
|
||||||
|
console.log('查询打印机信息:', computerInfo);
|
||||||
|
this.app.redis.del(key); // 删除旧的打印机信息
|
||||||
|
this.app.redis.set(key, JSON.stringify(data), 'EX', 300); // 设置过期时间为 5分钟
|
||||||
|
return this.successResponse('setting.setInfo', data, 'Token 验证成功');
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
return this.errorResponse('setting.refreshToken', error.message || 'Token 验证失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async refreshToken(data) {
|
||||||
|
const { token } = data;
|
||||||
|
console.log('AuthService.refreshToken called with oldToken:', token);
|
||||||
|
const { app } = this;
|
||||||
|
try {
|
||||||
|
// 验证旧 Token
|
||||||
|
const decoded = app.jwt.verify(token, app.config.jwt.secret);
|
||||||
|
const { code, printer, warehouse, computerId } = decoded;
|
||||||
|
const jwtToken = app.jwt.sign({ code, printer, warehouse, computerId }, app.config.jwt.secret, {
|
||||||
|
expiresIn: '1h',
|
||||||
|
});
|
||||||
|
return this.successResponse('setting.setToken', { token: jwtToken, tokenExpireTime: Date.now() + 3600 * 1000 }, 'Token 刷新成功');
|
||||||
|
} catch (error) {
|
||||||
|
console.log('Token 刷新失败:', error);
|
||||||
|
return this.errorResponse('setting.refreshToken', error.message || 'Token 刷新失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = AuthService;
|
||||||
133
app/service/base.js
Normal file
133
app/service/base.js
Normal file
@ -0,0 +1,133 @@
|
|||||||
|
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;
|
||||||
32
app/service/bind.js
Normal file
32
app/service/bind.js
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
const BaseService = require('./base');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
class BindService extends BaseService {
|
||||||
|
async generateCode() {
|
||||||
|
const { app, ctx } = this;
|
||||||
|
const uniqueId = ctx.uniqueId;
|
||||||
|
try {
|
||||||
|
// 生成随机码
|
||||||
|
const randomCode = crypto.randomBytes(3).toString('hex'); // 6位随机码
|
||||||
|
const key = `bind:${randomCode}`;
|
||||||
|
const expirationTime = 300; // 有效期 300 秒
|
||||||
|
|
||||||
|
// 存储对象到 Redis
|
||||||
|
const value = {
|
||||||
|
uniqueId,
|
||||||
|
randomCode,
|
||||||
|
createdAt: Date.now(),
|
||||||
|
expiresIn: expirationTime, // 失效时间
|
||||||
|
};
|
||||||
|
|
||||||
|
// 写入 Redis,设置有效期
|
||||||
|
await app.redis.set(key, JSON.stringify(value), 'EX', expirationTime);
|
||||||
|
return this.successResponse('bind.generateCode', value, '随机码生成成功');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('生成随机码时发生错误:', error);
|
||||||
|
return this.errorResponse('bind.generateCode', '随机码生成失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = BindService;
|
||||||
31
app/service/printerComponent.js
Normal file
31
app/service/printerComponent.js
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
const BaseService = require('./base');
|
||||||
|
|
||||||
|
class PrinterComponentService extends BaseService {
|
||||||
|
// ...existing methods...
|
||||||
|
|
||||||
|
async statusChange(data) {
|
||||||
|
const { name, status } = 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}:name:${name}:status`;
|
||||||
|
await app.redis.set(printerKey, status);
|
||||||
|
console.log(`打印机状态更新成功: ${computerId} -> ${status}`);
|
||||||
|
return {
|
||||||
|
status: 'success',
|
||||||
|
message: '打印机状态更新成功',
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`打印机状态更新失败: ${error.message}`);
|
||||||
|
return {
|
||||||
|
status: 'fail',
|
||||||
|
message: '打印机状态更新失败',
|
||||||
|
error: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = PrinterComponentService;
|
||||||
26
app/service/test.js
Normal file
26
app/service/test.js
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
const BaseService = require('./base');
|
||||||
|
|
||||||
|
class TestService extends BaseService {
|
||||||
|
async index(data) {
|
||||||
|
return this.successResponse('test.index', data, 'Test service index 方法调用成功');
|
||||||
|
}
|
||||||
|
|
||||||
|
async logToRedis(data) {
|
||||||
|
const {key, message} = data;
|
||||||
|
const { app } = this;
|
||||||
|
console.log(`准备写入 Redis,键: ${key}, 消息: ${message},redis对象:`, app.redis);
|
||||||
|
try {
|
||||||
|
await app.redis.set(key, message);
|
||||||
|
console.log(`日志已写入 Redis,键: ${key}, 消息: ${message}`);
|
||||||
|
return this.successResponse('logToRedis', { key, message }, '日志写入成功');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('写入 Redis 时发生错误:', error);
|
||||||
|
return this.errorResponse('logToRedis', '日志写入失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async ping(){
|
||||||
|
return this.successResponse('test.ping', 'pong', 'pong');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = TestService;
|
||||||
79
config/config.default.js
Normal file
79
config/config.default.js
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
/* eslint valid-jsdoc: "off" */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Egg.EggAppInfo} appInfo app info
|
||||||
|
*/
|
||||||
|
module.exports = appInfo => {
|
||||||
|
/**
|
||||||
|
* built-in config
|
||||||
|
* @type {Egg.EggAppConfig}
|
||||||
|
**/
|
||||||
|
const config = exports = {};
|
||||||
|
|
||||||
|
// use for cookie sign key, should change to your own and keep security
|
||||||
|
config.keys = appInfo.name + '_1772789382448_6777';
|
||||||
|
|
||||||
|
// add your middleware config here
|
||||||
|
config.cluster = {
|
||||||
|
listen: {
|
||||||
|
port: 4050, // 使用其他端口避免冲突
|
||||||
|
hostname: '0.0.0.0',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
// add your user config here
|
||||||
|
const userConfig = {
|
||||||
|
// myAppName: 'egg',
|
||||||
|
};
|
||||||
|
config.bodyParser = {
|
||||||
|
jsonLimit: '10mb', // 增大 JSON 体限制
|
||||||
|
formLimit: '10mb', // 增大表单限制
|
||||||
|
textLimit: '10mb', // 增大文本限制
|
||||||
|
enableTypes: ['json', 'form', 'text'],
|
||||||
|
extendTypes: {
|
||||||
|
json: ['application/json'],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
config.mysql = {
|
||||||
|
clients: {
|
||||||
|
wms: {
|
||||||
|
host: '127.0.0.1',
|
||||||
|
port: '3306',
|
||||||
|
user: 'wms',
|
||||||
|
password: 'P6j3YTHTpirepYWz',
|
||||||
|
database: 'wms',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
app: true,
|
||||||
|
agent: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
config.security = {
|
||||||
|
csrf: {
|
||||||
|
enable: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
config.redis = {
|
||||||
|
client: {
|
||||||
|
host: '127.0.0.1', // Redis服务器地址
|
||||||
|
port: 6379, // Redis端口
|
||||||
|
password: 'qwe2019@', // Redis密码(如果有)
|
||||||
|
db: 11, // 使用的数据库索引
|
||||||
|
},
|
||||||
|
};
|
||||||
|
config.websocket = {
|
||||||
|
// 使用 Redis 适配器
|
||||||
|
adapter: {
|
||||||
|
type: 'redis',
|
||||||
|
redis: config.redis.client, // 复用 Redis 配置
|
||||||
|
},
|
||||||
|
// 或者更简单的配置方式
|
||||||
|
redis: config.redis.client,
|
||||||
|
};
|
||||||
|
config.jwt = {
|
||||||
|
secret: 'E5#ex.g@,GfL_8?', // 请替换为自己的密钥
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
...config,
|
||||||
|
...userConfig,
|
||||||
|
};
|
||||||
|
};
|
||||||
23
config/plugin.js
Normal file
23
config/plugin.js
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
/** @type Egg.EggPlugin */
|
||||||
|
module.exports = {
|
||||||
|
// had enabled by egg
|
||||||
|
// static: {
|
||||||
|
// enable: true,
|
||||||
|
// }
|
||||||
|
websocket: {
|
||||||
|
enable: true,
|
||||||
|
package: 'egg-websocket-plugin',
|
||||||
|
},
|
||||||
|
redis: {
|
||||||
|
enable: true,
|
||||||
|
package: 'egg-redis',
|
||||||
|
},
|
||||||
|
jwt: {
|
||||||
|
enable: true,
|
||||||
|
package: 'egg-jwt',
|
||||||
|
},
|
||||||
|
mysql: {
|
||||||
|
enable: true,
|
||||||
|
package: 'egg-mysql',
|
||||||
|
},
|
||||||
|
};
|
||||||
5
jsconfig.json
Normal file
5
jsconfig.json
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"include": [
|
||||||
|
"**/*"
|
||||||
|
]
|
||||||
|
}
|
||||||
42
package.json
Normal file
42
package.json
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
{
|
||||||
|
"name": "services.printer",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "",
|
||||||
|
"private": true,
|
||||||
|
"egg": {
|
||||||
|
"declarations": true
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"egg": "^3.17.5",
|
||||||
|
"egg-jwt": "^3.1.7",
|
||||||
|
"egg-mysql": "^5.0.0",
|
||||||
|
"egg-redis": "^2.6.1",
|
||||||
|
"egg-scripts": "2",
|
||||||
|
"egg-websocket-plugin": "^3.0.0-beta.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"egg-bin": "6",
|
||||||
|
"egg-mock": "5",
|
||||||
|
"eslint": "8",
|
||||||
|
"eslint-config-egg": "13"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.0.0"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"start": "egg-scripts start --daemon --title=egg-server-services.printer",
|
||||||
|
"stop": "egg-scripts stop --title=egg-server-services.printer",
|
||||||
|
"dev": "egg-bin dev",
|
||||||
|
"test": "npm run lint -- --fix && npm run test:local",
|
||||||
|
"test:local": "egg-bin test",
|
||||||
|
"cov": "egg-bin cov",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"ci": "npm run lint && npm run cov"
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": ""
|
||||||
|
},
|
||||||
|
"author": "liufumingren",
|
||||||
|
"license": "MIT"
|
||||||
|
}
|
||||||
8
services.printer.code-workspace
Normal file
8
services.printer.code-workspace
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"folders": [
|
||||||
|
{
|
||||||
|
"path": "."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"settings": {}
|
||||||
|
}
|
||||||
BIN
services.printer.rar
Normal file
BIN
services.printer.rar
Normal file
Binary file not shown.
23
test/app/controller/home.test.js
Normal file
23
test/app/controller/home.test.js
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
const { strict: assert } = require('node:assert');
|
||||||
|
const path = require('node:path');
|
||||||
|
const { statSync } = require('node:fs');
|
||||||
|
const { app } = require('egg-mock/bootstrap');
|
||||||
|
|
||||||
|
describe('test/app/controller/home.test.js', () => {
|
||||||
|
it('should assert', async () => {
|
||||||
|
const pkg = require('../../../package.json');
|
||||||
|
assert(app.config.keys.startsWith(pkg.name));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should typings exists', async () => {
|
||||||
|
const typings = path.join(__dirname, '../../../typings');
|
||||||
|
assert(statSync(typings));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should GET /', async () => {
|
||||||
|
return app.httpRequest()
|
||||||
|
.get('/')
|
||||||
|
.expect('hi, egg')
|
||||||
|
.expect(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
x
Reference in New Issue
Block a user