ProtoUtils.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  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. let msg = msgType.create(data)
  11. let bytes = msgType.encode(msg).finish()
  12. return bytes
  13. }
  14. static Decode(msgTypeName, bytes) {
  15. let msgType = protores[game.protobufPackage][msgTypeName.replace('cmd_', '')]
  16. let msg = msgType.decode(bytes)
  17. let data = msgType.toObject(msg, {
  18. longs: Number, //long默认转换为Number类型
  19. enums: String,
  20. bytes: String,
  21. // see ConversionOptions
  22. })
  23. // 处理未定义的字段,有一个默认值
  24. let fucName = msgTypeName.replace('cmd_', '').replace(/_([a-z])/g, (match, char) => {
  25. return char.toUpperCase()
  26. })
  27. if (game[fucName]) {
  28. data = game[fucName].create(data)
  29. }
  30. return data
  31. }
  32. }