load protobuf.js JSON descriptor

This commit is contained in:
sovlookup 2021-03-12 19:39:06 +08:00
parent 17b43dfbfd
commit c2d7e4adda
3 changed files with 42 additions and 0 deletions

View File

@ -395,6 +395,23 @@ export function loadSync(
return createPackageDefinition(root, options!);
}
export function fromJSON(
json: Protobuf.INamespace,
root?: Protobuf.Root
): PackageDefinition {
const options: Options = json.options || {};
const newRoot: Protobuf.Root = root || new Protobuf.Root();
if (!!options.includeDirs) {
if (!Array.isArray(options.includeDirs)) {
throw new Error('The includeDirs option must be an array');
}
addIncludePathResolver(newRoot, options.includeDirs as string[]);
}
const loadedRoot = Protobuf.Root.fromJSON(json, newRoot);
loadedRoot.resolveAll();
return createPackageDefinition(newRoot, options!);
}
export function loadFileDescriptorSetFromBuffer(
descriptorSet: Buffer,
options?: Options

View File

@ -102,6 +102,15 @@ describe('Descriptor types', () => {
proto_loader.loadSync(`${TEST_PROTO_DIR}/well_known.proto`);
});
it('Can load JSON descriptors', () => {
// This is protobuf.js JSON descriptor
// https://github.com/protobufjs/protobuf.js#using-json-descriptors
const buffer = readFileSync(`${TEST_PROTO_DIR}/rpc.proto.json`);
const json = JSON.parse(buffer.toString());
// This will throw if the rpc descriptor JSON cannot be decoded
proto_loader.fromJSON(json);
});
it('Can load binary-encoded proto file descriptor sets', () => {
const buffer = readFileSync(`${TEST_PROTO_DIR}/rpc.desc.bin`);
// This will throw if the rpc descriptor cannot be decoded

View File

@ -0,0 +1,16 @@
{
"nested": {
"awesomepackage": {
"nested": {
"AwesomeMessage": {
"fields": {
"awesomeField": {
"type": "string",
"id": 1
}
}
}
}
}
}
}