# NestJS

> Serve a contract from Nest controllers with @trpc12/experimental-nest.

Experimental: Contracts and OpenAPI might change or go away in any release.

`@trpc12/experimental-nest` serves a contract from Nest controllers. `@Implement(contract)` adds the Nest route for the contract's REST mapping; the method returns the procedure, so the controller's injected services reach the resolver through `this`. The whole package is experimental, as its name says, so its exports have no prefix: it might change or go away in any release.

```package-install
@trpc12/trpc effect @trpc12/experimental-nest @nestjs/common @nestjs/core @effect/platform-node rxjs
```

```ts
import { Implement, TrpcModule } from '@trpc12/experimental-nest';

const impl = t.implement(appContract);

@Controller()
class PostController {
  constructor(@Inject(Posts) private readonly posts: Posts) {}

  @Implement(appContract.post.byId) // .meta({ route: { method: 'GET', path: '/posts/{id}' } })
  byId() {
    return impl.post.byId.query(
      (opts) =>
        this.posts.find(opts.input.id) ??
        opts.errors.NOT_FOUND({ data: { id: opts.input.id } }),
    );
  }
}

@Module({
  imports: [
    TrpcModule.forRoot({
      createContext: (opts) => ({
        user: opts.platform.switchToHttp().getRequest().user,
      }),
      layer: Db.layer,
    }),
  ],
  controllers: [PostController],
  providers: [Posts],
})
class AppModule {}
```

- A leaf needs a route `path`, `.meta({ route: { path } })`. Pass a contract router instead and return `impl.router({ … })` (or a plain object of procedures) to get default paths from the keys below it (`/post/byId`).
- `TrpcModule.forRoot()` takes the OpenAPI handler's options; `createContext`'s `platform` is Nest's `ExecutionContext`. `forRootAsync({ inject, useFactory })` builds them from providers. One handler serves every route, so the `layer` is built once and released on shutdown (`app.enableShutdownHooks()` or `app.close()`).
- Guards, pipes and filters run as usual; put `@Implement` above the method's other decorators so they apply to every route it adds. The procedure's own middleware and validation run after them, and errors use the REST shape above.
- Bodies Nest's JSON and urlencoded parsers read are used as parsed; others are read from the request.
- Express only. Nest needs `experimentalDecorators`.

Routes and errors follow the [OpenAPI handler](https://v12.trpc.io/v12/docs/openapi/routes.md).

The [`examples/experimental/nest`](https://github.com/trpc/trpc/blob/v12/next/examples/experimental/nest/README.md) app implements a contract in a controller, with a guard, an injected service and an Effect layer, and calls it with `experimental_openApiLink`.

## Credits

`@trpc12/experimental-nest` follows [oRPC's NestJS integration](https://orpc.dev/docs/integrations/nest).
