/** @format */ import * as protores from './protores' //import {protobufPackage} from './game' import * as game from './game' export class ProtoUtils { //packageName: package名 //msgTypeName: 消息类型名 static Encode(msgTypeName, data) { let msgType = protores[game.protobufPackage][msgTypeName.replace('cmd_', '')] if (!msgType) { msgType = protores[game.protobufPackage]['ping'] } let msg = msgType.create(data) let bytes = msgType.encode(msg).finish() return bytes } static Decode(msgTypeName, bytes) { let msgType = protores[game.protobufPackage][msgTypeName.replace('cmd_', '')] if (!msgType) return {} let msg = msgType.decode(bytes) let data = msgType.toObject(msg, { longs: Number, //long默认转换为Number类型 enums: String, bytes: String, // see ConversionOptions }) // 处理未定义的字段,有一个默认值 let fucName = msgTypeName.replace('cmd_', '').replace(/_([a-z])/g, (match, char) => { return char.toUpperCase() }) if (game[fucName]) { data = game[fucName].create(data) } return data } }