32 lines
832 B
TypeScript
32 lines
832 B
TypeScript
|
/**
|
||
|
*
|
||
|
* pb helper
|
||
|
*/
|
||
|
// import { Message } from 'protobufjs'
|
||
|
|
||
|
interface ProtoEncodable<T> {
|
||
|
create(data: T): unknown
|
||
|
encode(message: unknown): { finish(): Uint8Array }
|
||
|
decode(buffer: Uint8Array): T
|
||
|
}
|
||
|
|
||
|
// 将proto对象序列化成buffer
|
||
|
export class PbHelper {
|
||
|
static Encode<T>(protoClass: ProtoEncodable<T>, data: T): Uint8Array {
|
||
|
const message = protoClass.create(data)
|
||
|
return protoClass.encode(message).finish()
|
||
|
}
|
||
|
static Decode<T>(protoClass: ProtoEncodable<T>, buffer: Uint8Array): T {
|
||
|
return protoClass.decode(buffer)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// // 假设有一个生成的 Protobuf 类
|
||
|
// class UserMessage {
|
||
|
// static create(data: User) { /*...*/ }
|
||
|
// static encode(msg: unknown) { /*...*/ }
|
||
|
// }
|
||
|
|
||
|
// const data = { name: "Alice" };
|
||
|
// const buffer = PbHelper.encode(UserMessage, data); // 显式传入消息类
|