mirror of https://github.com/grpc/grpc-node.git
Avoid unused definition imports from proto-loader
Since proto files don't always contain all types of definition, it was possible to get into a state where generated code contained unused imports which caused TS errors. This change makes those imports conditional on the existence of the corresponding definitions in the proto file. Co-authored-by: Austin Puri <austin.puri@gmail.com> Co-authored-by: Joe Porpeglia <josephp@spotify.com> Signed-off-by: Mike Lewis <mtlewis@users.noreply.github.com>
This commit is contained in:
parent
740bd683bb
commit
f289c343b3
|
@ -579,6 +579,34 @@ function generateServiceInterfaces(formatter: TextFormatter, serviceType: Protob
|
|||
generateServiceDefinitionInterface(formatter, serviceType);
|
||||
}
|
||||
|
||||
function containsDefinition(definitionType: typeof Protobuf.Type | typeof Protobuf.Enum, namespace: Protobuf.NamespaceBase): boolean {
|
||||
for (const nested of namespace.nestedArray.sort(compareName)) {
|
||||
if (nested instanceof definitionType) {
|
||||
return true;
|
||||
} else if (isNamespaceBase(nested) && !(nested instanceof Protobuf.Type) && !(nested instanceof Protobuf.Enum)) {
|
||||
return containsDefinition(definitionType, nested);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function generateDefinitionImports(formatter: TextFormatter, namespace: Protobuf.NamespaceBase, options: GeneratorOptions) {
|
||||
const imports = [];
|
||||
|
||||
if (containsDefinition(Protobuf.Enum, namespace)) {
|
||||
imports.push('EnumTypeDefinition');
|
||||
}
|
||||
|
||||
if (containsDefinition(Protobuf.Type, namespace)) {
|
||||
imports.push('MessageTypeDefinition');
|
||||
}
|
||||
|
||||
if (imports.length) {
|
||||
formatter.writeLine(`import type { ${imports.join(', ')} } from '@grpc/proto-loader';`);
|
||||
}
|
||||
}
|
||||
|
||||
function generateServiceImports(formatter: TextFormatter, namespace: Protobuf.NamespaceBase, options: GeneratorOptions) {
|
||||
for (const nested of namespace.nestedArray.sort(compareName)) {
|
||||
if (nested instanceof Protobuf.Service) {
|
||||
|
@ -617,7 +645,7 @@ function generateLoadedDefinitionTypes(formatter: TextFormatter, namespace: Prot
|
|||
|
||||
function generateRootFile(formatter: TextFormatter, root: Protobuf.Root, options: GeneratorOptions) {
|
||||
formatter.writeLine(`import type * as grpc from '${options.grpcLib}';`);
|
||||
formatter.writeLine("import type { ServiceDefinition, EnumTypeDefinition, MessageTypeDefinition } from '@grpc/proto-loader';");
|
||||
generateDefinitionImports(formatter, root, options);
|
||||
formatter.writeLine('');
|
||||
|
||||
generateServiceImports(formatter, root, options);
|
||||
|
|
Loading…
Reference in New Issue