1 | import { existsSync } from 'fs';
|
2 | import { dirname, parse, resolve } from 'path';
|
3 | import { Root } from 'protobufjs';
|
4 |
|
5 | export function resolveImportPath(origin: string, target: string): string {
|
6 | let currentDir = dirname(origin);
|
7 |
|
8 | while (
|
9 | !existsSync(resolve(currentDir, target)) &&
|
10 | parse(currentDir).root !== currentDir
|
11 | ) {
|
12 | currentDir = resolve(currentDir, '..');
|
13 | }
|
14 |
|
15 | return resolve(currentDir, target);
|
16 | }
|
17 |
|
18 | export function encodeProto(
|
19 | protoDefPath: string,
|
20 | attributes: {},
|
21 | outerClass: string,
|
22 | ): Buffer {
|
23 | const root = new Root();
|
24 | root.resolvePath = resolveImportPath;
|
25 | root.loadSync(protoDefPath);
|
26 | const messageType = root.lookupType(outerClass);
|
27 |
|
28 | const errMsg = messageType.verify(attributes);
|
29 | if (errMsg) {
|
30 | throw Error(errMsg);
|
31 | }
|
32 |
|
33 | const message = messageType.fromObject(attributes);
|
34 | return Buffer.from(messageType.encode(message).finish());
|
35 | }
|
36 |
|
37 | export function encodeProtoWithEncoding(
|
38 | protoDefPath: string,
|
39 | attributes: {},
|
40 | outerClass: string,
|
41 | encoding: string,
|
42 | ): string {
|
43 | const root = new Root();
|
44 | root.resolvePath = resolveImportPath;
|
45 | root.loadSync(protoDefPath);
|
46 | const messageType = root.lookupType(outerClass);
|
47 |
|
48 | const errMsg = messageType.verify(attributes);
|
49 | if (errMsg) {
|
50 | throw Error(errMsg);
|
51 | }
|
52 |
|
53 | const message = messageType.fromObject(attributes);
|
54 | const messageBuffer = Buffer.from(messageType.encode(message).finish());
|
55 | return messageBuffer.toString(encoding);
|
56 | }
|
57 |
|
58 | export function decodeProto(
|
59 | protoDefPath: string,
|
60 | outerClass: string,
|
61 | buffer: Uint8Array,
|
62 | ): { [k: string]: unknown } {
|
63 | const root = new Root();
|
64 | root.resolvePath = resolveImportPath;
|
65 | root.loadSync(protoDefPath);
|
66 | const messageType = root.lookupType(outerClass);
|
67 | const message = messageType.decode(buffer);
|
68 | const messageObject = messageType.toObject(message);
|
69 |
|
70 | const errMsg = messageType.verify(messageObject);
|
71 | if (errMsg) {
|
72 | throw Error(errMsg);
|
73 | }
|
74 |
|
75 | return messageObject;
|
76 | }
|