Skip to content

Commit

Permalink
Avoid unused definition imports from proto-loader
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
3 people committed Jun 23, 2021
1 parent 740bd68 commit f289c34
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion packages/proto-loader/bin/proto-loader-gen-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit f289c34

Please sign in to comment.