|
| 1 | +=== tRPC |
| 2 | + |
| 3 | +The tRPC module provides end-to-end type safety by integrating the https://trpc.io/[tRPC] protocol directly into Jooby. |
| 4 | + |
| 5 | +Because the `io.jooby.trpc` package is included in Jooby core, there are no extra dependencies to add to your project. This integration allows you to write standard Java/Kotlin controllers and consume them directly in the browser using the official `@trpc/client`—complete with 100% type safety, autocomplete, and zero manual client generation. |
| 6 | + |
| 7 | +==== Usage |
| 8 | + |
| 9 | +Because tRPC relies heavily on JSON serialization to communicate with the frontend client, a JSON module **must** be installed prior to the `TrpcModule`. |
| 10 | + |
| 11 | +NOTE: Currently, Jooby only provides the required `TrpcParser` SPI implementation for two JSON engines: **Jackson 2/3** and **AvajeJsonbModule** . Using other JSON modules (like Gson) will result in a missing service exception at startup. |
| 12 | + |
| 13 | +[source, java] |
| 14 | +---- |
| 15 | +import io.jooby.Jooby; |
| 16 | +import io.jooby.json.JacksonModule; |
| 17 | +import io.jooby.trpc.TrpcModule; |
| 18 | +
|
| 19 | +public class App extends Jooby { |
| 20 | + { |
| 21 | + install(new JacksonModule()); // <1> |
| 22 | +
|
| 23 | + install(new TrpcModule()); // <2> |
| 24 | +
|
| 25 | + install(new MovieService_()); // <3> |
| 26 | + } |
| 27 | +} |
| 28 | +---- |
| 29 | + |
| 30 | +1. Install a supported JSON engine (Jackson or Avaje) |
| 31 | +2. Install the tRPC extension |
| 32 | +3. Register your @Trpc annotated controllers (using the APT generated route) |
| 33 | + |
| 34 | +==== Writing a Service |
| 35 | + |
| 36 | +You can define your procedures using explicit tRPC annotations or a hybrid approach combining tRPC with standard HTTP methods: |
| 37 | + |
| 38 | +* **Explicit Annotations:** Use `@Trpc.Query` (maps to `GET`) and `@Trpc.Mutation` (maps to `POST`). |
| 39 | +* **Hybrid Annotations:** Combine the base `@Trpc` annotation with Jooby's standard HTTP annotations. A `@GET` resolves to a tRPC query, while state-changing methods (`@POST`, `@PUT`, `@DELETE`) resolve to tRPC mutations. |
| 40 | + |
| 41 | +.MovieService |
| 42 | +[source, java] |
| 43 | +---- |
| 44 | +import io.jooby.annotation.Trpc; |
| 45 | +import io.jooby.annotation.DELETE; |
| 46 | +
|
| 47 | +public record Movie(int id, String title, int year) {} |
| 48 | +
|
| 49 | +@Trpc("movies") // Defines the 'movies' namespace |
| 50 | +public class MovieService { |
| 51 | +
|
| 52 | + // 1. Explicit tRPC Query |
| 53 | + @Trpc.Query |
| 54 | + public Movie getById(int id) { |
| 55 | + return new Movie(id, "Pulp Fiction", 1994); |
| 56 | + } |
| 57 | +
|
| 58 | + // 2. Explicit tRPC Mutation |
| 59 | + @Trpc.Mutation |
| 60 | + public Movie create(Movie movie) { |
| 61 | + // Save to database logic here |
| 62 | + return movie; |
| 63 | + } |
| 64 | +
|
| 65 | + // 3. Hybrid Mutation |
| 66 | + @Trpc |
| 67 | + @DELETE |
| 68 | + public void delete(int id) { |
| 69 | + // Delete from database |
| 70 | + } |
| 71 | +} |
| 72 | +---- |
| 73 | + |
| 74 | +==== Build Tool Configuration |
| 75 | + |
| 76 | +To generate the `trpc.d.ts` TypeScript definitions, you must configure the Jooby build plugin for your project. The generator parses your source code and emits the definitions during the compilation phase. |
| 77 | + |
| 78 | +.pom.xml |
| 79 | +[source, xml, role = "primary", subs="verbatim,attributes"] |
| 80 | +---- |
| 81 | +<plugin> |
| 82 | + <groupId>io.jooby</groupId> |
| 83 | + <artifactId>jooby-maven-plugin</artifactId> |
| 84 | + <version>${jooby.version}</version> |
| 85 | + <executions> |
| 86 | + <execution> |
| 87 | + <goals> |
| 88 | + <goal>trpc</goal> |
| 89 | + </goals> |
| 90 | + </execution> |
| 91 | + </executions> |
| 92 | + <configuration> |
| 93 | + <jsonLibrary>jackson2</jsonLibrary> |
| 94 | + <outputDir>${project.build.outputDirectory}</outputDir> |
| 95 | + </configuration> |
| 96 | +</plugin> |
| 97 | +---- |
| 98 | + |
| 99 | +.gradle.build |
| 100 | +[source, groovy, role = "secondary", subs="verbatim,attributes"] |
| 101 | +---- |
| 102 | +plugins { |
| 103 | + id 'io.jooby.trpc' version "${joobyVersion}" |
| 104 | +} |
| 105 | +
|
| 106 | +trpc { |
| 107 | + // Optional settings |
| 108 | + jsonLibrary = 'jackson2' |
| 109 | +} |
| 110 | +---- |
| 111 | + |
| 112 | +==== Consuming the API (Frontend) |
| 113 | + |
| 114 | +Once the project is compiled, the build plugin generates a `trpc.d.ts` file containing your exact `AppRouter` shape. You can then use the official client in your TypeScript frontend: |
| 115 | + |
| 116 | +[source, bash] |
| 117 | +---- |
| 118 | +npm install @trpc/client |
| 119 | +---- |
| 120 | + |
| 121 | +[source, typescript] |
| 122 | +---- |
| 123 | +import { createTRPCProxyClient, httpLink } from '@trpc/client'; |
| 124 | +import type { AppRouter } from './target/classes/trpc'; // Path to generated file |
| 125 | +
|
| 126 | +// Initialize the strongly-typed client |
| 127 | +export const trpc = createTRPCProxyClient<AppRouter>({ |
| 128 | + links: [ |
| 129 | + httpLink({ |
| 130 | + url: 'http://localhost:8080/trpc', |
| 131 | + }), |
| 132 | + ], |
| 133 | +}); |
| 134 | +
|
| 135 | +// 100% Type-safe! IDEs will autocomplete namespaces, inputs, and outputs. |
| 136 | +const movie = await trpc.movies.getById.query(1); |
| 137 | +console.log(`Fetched: ${movie.title} (${movie.year})`); |
| 138 | +---- |
| 139 | + |
| 140 | +==== Advanced Configuration |
| 141 | + |
| 142 | +===== Custom Exception Mapping |
| 143 | +The tRPC protocol expects specific JSON-RPC error codes (e.g., `-32600` for Bad Request). `TrpcModule` automatically registers a specialized error handler to format these errors. |
| 144 | + |
| 145 | +If you throw custom domain exceptions, you can map them directly to tRPC error codes using the service registry so the frontend client receives the correct error state: |
| 146 | + |
| 147 | +[source, java] |
| 148 | +---- |
| 149 | +import io.jooby.trpc.TrpcErrorCode; |
| 150 | +
|
| 151 | +{ |
| 152 | + install(new TrpcModule()); |
| 153 | +
|
| 154 | + // Map your custom business exception to a standard tRPC error code |
| 155 | + getServices().mapOf(Class.class, TrpcErrorCode.class) |
| 156 | + .put(IllegalArgumentException.class, TrpcErrorCode.BAD_REQUEST) |
| 157 | + .put(MovieNotFoundException.class, TrpcErrorCode.NOT_FOUND); |
| 158 | +} |
| 159 | +---- |
| 160 | + |
| 161 | +===== Custom TypeScript Mappings |
| 162 | +Sometimes you have custom Java types (like `java.util.UUID` or `java.math.BigDecimal`) that you want translated into specific TypeScript primitives. You can define these overrides in your build tool: |
| 163 | + |
| 164 | +**Maven:** |
| 165 | +[source, xml] |
| 166 | +---- |
| 167 | +<configuration> |
| 168 | + <customTypeMappings> |
| 169 | + <java.util.UUID>string</java.util.UUID> |
| 170 | + <java.math.BigDecimal>number</java.math.BigDecimal> |
| 171 | + </customTypeMappings> |
| 172 | +</configuration> |
| 173 | +---- |
| 174 | + |
| 175 | +**Gradle:** |
| 176 | +[source, groovy] |
| 177 | +---- |
| 178 | +trpc { |
| 179 | + customTypeMappings = [ |
| 180 | + 'java.util.UUID': 'string', |
| 181 | + 'java.math.BigDecimal': 'number' |
| 182 | + ] |
| 183 | +} |
| 184 | +---- |
0 commit comments