better_grpc_generator

A simple way to use the server implementation of grpc as a offline one as well! It takes the generated files from protoc compiler and does the code generation from it. So, you will have to have protoc installed to use this tool.

Install

Currently only tested on 3.12.4 but should work on greater versions.

  • compile grpc from .proto files

You can look at Regenerate gRPC code

or use do like that:

protoc --dart_out=grpc:lib/src/generated -Iprotos protos/helloworld.proto
  • add it better_grpc_generator to your pubspec.yaml
dev_dependencies:
  better_grpc_generator: ^0.0.1
  build_runner: ^2.1.11
  • get it
dart pub get

Usage

  • generate the code!
dart run build_runner build --delete-conflicting-outputs

Using the generated code

This tool generate classes with the prefix Better so, let's say your service name is Hello for example, normally you'd use HelloServiceBase but here you use BetterHelloServiceBase and implement the actual functionality for your server, like this:

class HelloService extends BetterHelloServiceBase {
    ...
}

This isn't a service by itself, to make a service just combine it with BetterHelloService.

final service = BetterHelloService(HelloService());

Now you can use this service as you'd usually do, but to make things more easier.

Create a server

final server = Server([
    BetterHelloService(HelloService()),
  ]);
await server.serve(port: port);
print('Server listening on port ${server.port}...');

Connect to the server

final channel = ClientChannel(
    'localhost',
    port: port,
    options: ChannelOptions(
      credentials: ChannelCredentials.insecure(),
    ),
  );
final client = BetterHelloClient(HelloClient(channel));

Create offline server

Here the word Client doesn't mean that it connectes to a server. It's just for reference that this class is extendsed from BetterHelloClientBase.

final offlineClient = BetterHelloOfflineClient(HelloService());

Why this exists?

You ask what the benefit of doing this?

Well.. doing this will save you time when developing applications that need to use offline and online connections using the same logic.

Here all the offline and the online clients are inherited from the same class so that it makes it more easy to deal with.

Other notes

  • The tool parses the generated files from protoc that only have the extension .pbgrpc.dart.

Libraries

builder
Support for doing something awesome.