Add functions for loading and parsing binary-encoded file decriptor sets

Fixes #1627
This commit is contained in:
A. Tate Barber 2020-11-22 17:29:14 -06:00
parent 1e37fbd3d2
commit 08254e4d2e
4 changed files with 72 additions and 0 deletions

View File

@ -30,6 +30,17 @@ declare module 'protobufjs' {
descriptor.IDescriptorProto;
}
interface RootConstructor {
new (options?: Options): Root;
fromDescriptor(
descriptorSet:
| descriptor.IFileDescriptorSet
| Protobuf.Reader
| Uint8Array
): Root;
fromJSON(json: Protobuf.INamespace, root?: Root): Root;
}
interface Root {
toDescriptor(
protoVersion: string
@ -368,6 +379,38 @@ export function loadSync(
return createPackageDefinition(root, options!);
}
export async function loadFileDescriptorSet(
descriptorSet: Protobuf.Message<descriptor.IFileDescriptorSet> &
descriptor.IFileDescriptorSet,
options?: Options
): Promise<PackageDefinition> {
options = options || {};
const root = (Protobuf.Root as Protobuf.RootConstructor).fromDescriptor(
descriptorSet
);
root.resolveAll();
return createPackageDefinition(root, options);
}
export function loadFileDescriptorSetFile(
filename: string,
options?: Options
): Promise<PackageDefinition> {
return new Promise((resolve, reject) => {
fs.readFile(filename, (err, data) => {
if (err) {
return reject(err);
}
const descriptorSet = descriptor.FileDescriptorSet.decode(
data
) as Protobuf.Message<descriptor.IFileDescriptorSet> &
descriptor.IFileDescriptorSet;
return resolve(loadFileDescriptorSet(descriptorSet, options));
});
});
}
// Load Google's well-known proto files that aren't exposed by Protobuf.js.
// Protobuf.js exposes: any, duration, empty, field_mask, struct, timestamp,

View File

@ -99,4 +99,9 @@ describe('Descriptor types', () => {
// This will throw if the well known protos are not available.
proto_loader.loadSync(`${TEST_PROTO_DIR}/well_known.proto`);
});
it('Can load binary-encoded proto file descriptor sets', () => {
// This will throw if the well known protos are not available.
proto_loader.loadFileDescriptorSetFile(`${TEST_PROTO_DIR}/rpc.desc`);
});
});

View File

@ -0,0 +1,11 @@
˜
test_protos/rpc.proto"
MyRequest
path ( Rpath"$
MyResponse
status (Rstatus20
MyService#
MyMethod
.MyRequest .MyResponsebproto3

View File

@ -0,0 +1,13 @@
syntax = "proto3";
service MyService {
rpc MyMethod (MyRequest) returns (MyResponse);
}
message MyRequest {
string path = 1;
}
message MyResponse {
int32 status = 2;
}