ProtoUtils.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /** @format */
  2. import * as protores from './protores'
  3. //import {protobufPackage} from './game'
  4. import * as game from './game'
  5. export class ProtoUtils {
  6. //packageName: package名
  7. //msgTypeName: 消息类型名
  8. static Encode(msgTypeName, data) {
  9. let msgType = protores[game.protobufPackage][msgTypeName.replace('cmd_', '')]
  10. if (!msgType) {
  11. msgType = protores[game.protobufPackage]['ping']
  12. }
  13. let msg = msgType.create(data)
  14. let bytes = msgType.encode(msg).finish()
  15. return bytes
  16. }
  17. static Decode(msgTypeName, bytes) {
  18. let msgType = protores[game.protobufPackage][msgTypeName.replace('cmd_', '')]
  19. if (!msgType) return {}
  20. let msg = msgType.decode(bytes)
  21. let data = msgType.toObject(msg, {
  22. longs: Number, //long默认转换为Number类型
  23. enums: String,
  24. bytes: String,
  25. // see ConversionOptions
  26. })
  27. // 处理未定义的字段,有一个默认值
  28. let fucName = msgTypeName.replace('cmd_', '').replace(/_([a-z])/g, (match, char) => {
  29. return char.toUpperCase()
  30. })
  31. if (game[fucName]) {
  32. data = game[fucName].create(data)
  33. }
  34. return data
  35. }
  36. }