@nixjs23n6/grpc-socket-core
Version:
gRPC for Web Clients.
83 lines • 2.94 kB
JavaScript
import protobuf from "protobufjs";
import { v4 as uuidv4 } from "uuid";
import { WSEnums } from "./enums";
export class Proto {
constructor() {
this.subscribers = [];
this.encoderDecoder = {};
}
subscribe(callback) {
this.subscribers.push(callback);
}
_readProto(nestedRoot, resolve, reject, root, executeEncoderDecoderMap) {
if (root && root.nested && root.nested[nestedRoot]) {
this.protoRoot = root.nested[nestedRoot];
this.Msg = this.protoRoot.Msg;
this.MsgType = this.protoRoot.MsgType;
if (typeof executeEncoderDecoderMap === "function")
executeEncoderDecoderMap(this);
if (Object.keys(this.encoderDecoder).length === 0) {
return reject(WSEnums.ProtoState.MESSAGE_ENCODERS_FAILED);
}
return resolve(WSEnums.ProtoState.READY);
}
return reject(WSEnums.ProtoState.NOT_YET);
}
init(nestedRoot = "ws", protoFile, protoJSONFallback, executeEncoderDecoderMap) {
return new Promise((resolve, reject) => {
if (!protoFile) {
if (protoJSONFallback && Object.keys(protoJSONFallback).length > 0) {
const root = protobuf.Root.fromJSON(protoJSONFallback);
this._readProto(nestedRoot, resolve, reject, root, executeEncoderDecoderMap);
}
return reject(WSEnums.ProtoState.PROTO_NOT_FOUND);
}
protobuf.load(protoFile, (err, root) => {
if (err) {
return reject(WSEnums.ProtoState.NOT_YET);
}
this._readProto(nestedRoot, resolve, reject, root, executeEncoderDecoderMap);
});
});
}
_getCurrentUnixTimestamp() {
return new Date().getTime();
}
buildMsg(type, data, msgId) {
let id = !msgId ? this.generateId() : msgId;
id = id.toString();
const encoder = this.encoderDecoder[type];
if (!encoder) {
return null;
}
return this.Msg.encode({
id,
type,
data: encoder.encode(data).finish(),
}).finish();
}
generateId() {
return `${this._getCurrentUnixTimestamp()}-${uuidv4()}`;
}
createPingMessage() {
return this.buildMsg(this.MsgType.PING);
}
decodeMsg(buffer) {
const msg = this.Msg.decode(new Uint8Array(buffer));
const { data, type } = msg;
msg.data = this.decodeData(data, type);
return msg;
}
decodeData(data, type) {
if (!data || !type)
return null;
const newData = new Uint8Array(data);
const decoder = this.encoderDecoder[type];
if (!decoder) {
return null;
}
return decoder.decode(newData);
}
}
export const proto = new Proto();
//# sourceMappingURL=proto.js.map