UNPKG

2.1 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var fs_1 = require("fs");
4var path_1 = require("path");
5var protobufjs_1 = require("protobufjs");
6function resolveImportPath(origin, target) {
7 var currentDir = path_1.dirname(origin);
8 while (!fs_1.existsSync(path_1.resolve(currentDir, target)) &&
9 path_1.parse(currentDir).root !== currentDir) {
10 currentDir = path_1.resolve(currentDir, '..');
11 }
12 return path_1.resolve(currentDir, target);
13}
14exports.resolveImportPath = resolveImportPath;
15function encodeProto(protoDefPath, attributes, outerClass) {
16 var root = new protobufjs_1.Root();
17 root.resolvePath = resolveImportPath;
18 root.loadSync(protoDefPath);
19 var messageType = root.lookupType(outerClass);
20 var errMsg = messageType.verify(attributes);
21 if (errMsg) {
22 throw Error(errMsg);
23 }
24 var message = messageType.fromObject(attributes);
25 return Buffer.from(messageType.encode(message).finish());
26}
27exports.encodeProto = encodeProto;
28function encodeProtoWithEncoding(protoDefPath, attributes, outerClass, encoding) {
29 var root = new protobufjs_1.Root();
30 root.resolvePath = resolveImportPath;
31 root.loadSync(protoDefPath);
32 var messageType = root.lookupType(outerClass);
33 var errMsg = messageType.verify(attributes);
34 if (errMsg) {
35 throw Error(errMsg);
36 }
37 var message = messageType.fromObject(attributes);
38 var messageBuffer = Buffer.from(messageType.encode(message).finish());
39 return messageBuffer.toString(encoding);
40}
41exports.encodeProtoWithEncoding = encodeProtoWithEncoding;
42function decodeProto(protoDefPath, outerClass, buffer) {
43 var root = new protobufjs_1.Root();
44 root.resolvePath = resolveImportPath;
45 root.loadSync(protoDefPath);
46 var messageType = root.lookupType(outerClass);
47 var message = messageType.decode(buffer);
48 var messageObject = messageType.toObject(message);
49 var errMsg = messageType.verify(messageObject);
50 if (errMsg) {
51 throw Error(errMsg);
52 }
53 return messageObject;
54}
55exports.decodeProto = decodeProto;