import { v4 } from 'uuid' import { Package50 } from '@/utils/websocket/package' import { FunCode } from '@/constants/enum/funcode' import { sessionData } from '@/stores' import { IMessageHead } from './protobuf/proto' import { TradeRequest, TradeResponse } from './interface' import Protobuf from './protobuf' import socket from '../index' /** * 构建消息头部 */ function getProtoHeader(funCode: keyof typeof FunCode, header?: IMessageHead, marketId?: number) { // 组合请求头 const protoHeader: IMessageHead = { FunCode: FunCode[funCode], UUID: v4(), AccessID: 0, UserID: sessionData.getLoginInfo('UserID'), ...(header ?? {}) } if (marketId) { protoHeader.MarketID = marketId; } return protoHeader; } /** * 向交易服务器发送请求 * @param params 请求参数 * @param reqCode 请求代码 * @param rspCode 回调代码 * @param marketId 市场ID */ function tradeServerMiddleware(reqCode: keyof typeof FunCode, rspCode: keyof typeof FunCode, params: TradeRequest, marketId?: number): Promise { params.data.Header = getProtoHeader(reqCode, params.data.Header, marketId); console.log(reqCode, FunCode[reqCode], params.data); return new Promise((resolve, reject) => { Protobuf.requestEncode(reqCode, params.data).then((res) => { // 发送消息 socket.sendTradeServer({ data: { payload: new Package50(FunCode[reqCode], res) }, success: (raw) => { Protobuf.responseDecode(rspCode, raw.content).then((res) => { console.log(rspCode, FunCode[rspCode], res); resolve(res); }).catch((msg) => { console.warn(rspCode, msg); reject('报文解析失败'); }) }, fail: (err) => { console.error(reqCode, err); reject(err); } }) }).catch((msg) => { console.error(reqCode, msg); reject('报文构建失败'); }) }) } /** * 向交易服务器发送请求 * @param params * @param reqCode * @param rspCode * @param marketId */ export async function tradeServerRequest(reqCode: keyof typeof FunCode, rspCode: keyof typeof FunCode, params: TradeRequest, marketId?: number) { const { success, fail, complete } = params; await tradeServerMiddleware(reqCode, rspCode, params, marketId).then((res) => { const { RetCode, RetDesc } = res; switch (RetCode) { case 0: { success && success(res); return Promise.resolve(); } case -1: { // 管理端错误消息 return Promise.reject(RetDesc); } case 12018: { if (RetDesc) { // 解析base64 res.RetDesc = Buffer.from(RetDesc, 'base64').toString(); } return Promise.reject(res.RetDesc); } default: { const msg = (RetDesc || RetCode).toString(); return Promise.reject(msg); } } }).catch((err) => { fail && fail(err); return Promise.reject(err); }).finally(() => { complete && complete(); }) }