|
| 1 | +# Public services with private implementations |
| 2 | + |
| 3 | +Learn how to create a `public` gRPC service with private implementation details. |
| 4 | + |
| 5 | +## Overview |
| 6 | + |
| 7 | +It's not uncommon for a library to provide a gRPC service as part of its API. |
| 8 | +For example, the gRPC Swift Extras package provides implementations of the gRPC |
| 9 | +health and reflection services. Making the implementation of a service `public` |
| 10 | +would require its generated gRPC and message types to also be `public`. This is |
| 11 | +undesirable as it leaks implementation details into the public API of the |
| 12 | +package. This article explains how to keep the generated types private while |
| 13 | +making the service available as part of the public API. |
| 14 | + |
| 15 | +## Hiding the implementation |
| 16 | + |
| 17 | +You can hide the implementation details of your service by providing a wrapper |
| 18 | +type conforming to `RegistrableRPCService`. This is the protocol used by |
| 19 | +`GRPCServer` to register service methods with the server's router. Implementing |
| 20 | +`RegistrableRPCService` is straightforward and can delegate to the underlying |
| 21 | +service. This is demonstrated in the following code: |
| 22 | + |
| 23 | +```swift |
| 24 | +public struct GreeterService: RegistrableRPCService { |
| 25 | + private var base: Greeter |
| 26 | + |
| 27 | + public init() { |
| 28 | + self.base = Greeter() |
| 29 | + } |
| 30 | + |
| 31 | + public func registerMethods<Transport>( |
| 32 | + with router: inout RPCRouter<Transport> |
| 33 | + ) where Transport: ServerTransport { |
| 34 | + self.base.registerMethods(with: &router) |
| 35 | + } |
| 36 | +} |
| 37 | +``` |
| 38 | + |
| 39 | +In this example `Greeter` implements the underlying service and would conform to |
| 40 | +the generated service protocol but would have a non-public access level. |
| 41 | +`GreeterService` is a public wrapper type conforming to `RegistrableRPCService` |
| 42 | +which implements its only requirement, `registerMethods(with:)`, by calling |
| 43 | +through to the underlying implementation. The result is a service which can be |
| 44 | +registered with a server where none of the generated types are part of the |
| 45 | +public API. |
0 commit comments