GraphQL
A self-composing schema, resolvers as structs, queries and mutations on one impl block.
Write a resolver as a struct and decorate it with #[resolver]; its
operations register themselves into the schema at boot — there is no
central queries = [...] list to keep in sync. Root resolvers
(#[query], #[mutation]) and entity-field resolvers
(#[field_resolver]) live on the same impl block. The schema composes
itself from a link-time registry, the playground self-mounts in dev,
and the SDL is committed.
nest-rs-graphql builds on async-graphql
— the framework wraps it so resolvers register themselves and inject
providers like any other struct, and serves it over its own HTTP transport.
Install
Section titled “Install”cargo add nest-rs --features graphql,seaorm,authzOne line in the feature crate’s manifest. graphql alone runs a resolver over a
hand-written service and compiles no database; add seaorm when the resolver
binds an entity, authz when an operation carries #[authorize] — features you
enable because your code says so, and that the decorator names when one is
missing.
#[operations] builds on async-graphql’s own #[Object], and a third-party
macro expands against your prelude — so the decorator pins that expansion to
the framework’s re-export (crate = "::nest_rs::graphql::async_graphql").
Reach async-graphql’s types the same way and the line above stays the only one:
use nest_rs::graphql::async_graphql::{Context, Result};Declare async-graphql = "7.2" yourself only when you write its derives by
hand (#[derive(SimpleObject)] on a type of your own) — a derive you wrote
expands against your prelude, exactly like serde’s. A build without seaorm
declares it too, with features = ["uuid", "chrono"], when a Uuid or a chrono
DateTime crosses the schema. Those scalars are async-graphql’s own, and
seaorm turns them on for its entities.
The minimal resolver
Section titled “The minimal resolver”use nest_rs::graphql::{operations, resolver};
#[resolver]pub struct GreetingResolver;
#[operations]impl GreetingResolver { #[query] #[public] async fn greeting(&self, name: Option<String>) -> String { format!("Hello, {}!", name.as_deref().unwrap_or("World")) }}#[resolver]on the struct registers it with the schema discovery registry.#[operations]on the impl block orchestrates the operations within — one decorator per item shape, exactly like#[controller]/#[routes].#[query]declares a top-level query. The method name becomes the field name (camelCased on the wire:greeting).#[public]declares the operation’s access posture — a caller with no credential is admitted, and it reads nothing a grant guards. Every#[query]/#[mutation]carries a posture: that,#[authorize(Action, Subject)](ability gate, and reads under the caller’s ability) or#[public(Action, Subject)]; a method with none does not compile.- Arguments are mapped to GraphQL input arguments by serde.
Option<T>becomes nullable.
#[query], #[mutation], #[field_resolver], #[public],
#[authorize] and #[inject] are inner attributes the two macros
consume in place — there is nothing to import for them. Only resolver
and operations (and crud / dataloader on the pages that use them)
come from nest_rs::graphql.
The resolver’s adapter module lists it, and the app imports the adapter:
use nest_rs::core::module;
use super::resolver::GreetingResolver;
#[module(providers = [GreetingResolver])]pub struct GreetingGraphqlModule;use nest_rs::core::module;use features::greeting::GreetingGraphqlModule;
#[module(imports = [GreetingGraphqlModule])]pub struct GreetingsAppModule;The resolver brings GraphqlModule, which mounts POST /graphql (the endpoint)
and, when the playground is on, GET /graphql for the interactive client, on the
HTTP server it imports: importing the adapter is all the app does. However many
resolvers bring it, the endpoint mounts once; the app writes
GraphqlModule::for_root(cfg) only to pin a GraphqlConfig.
Run it
Section titled “Run it”$ curl -sX POST http://localhost:3000/graphql \ -H 'Content-Type: application/json' \ -d '{"query":"{ greeting(name: \"Ada\") }"}'{"data":{"greeting":"Hello, Ada!"}}Under a declared development profile — nestrs run dev declares it — open
http://localhost:3000/graphql for the
playground.
Injecting a service
Section titled “Injecting a service”A resolver injects providers like any other struct:
use std::sync::Arc;use nest_rs::graphql::{operations, resolver};use crate::greeting::service::GreetingService;
#[resolver]pub struct GreetingResolver { #[inject] svc: Arc<GreetingService>,}
#[operations]impl GreetingResolver { #[query] #[public] async fn greeting(&self, name: Option<String>) -> String { self.svc.greet(name.as_deref().unwrap_or("World")) }}The container resolves GreetingService from the import tree. No
container handle to thread, no factory to call.
In this section
Section titled “In this section”Basics
Section titled “Basics”- Queries and mutations —
#[query],#[mutation], inputs, outputs, returning typed entities. - Services and context — the service an operation injects, and the caller, scope and loaders it reads.
- Field resolvers — custom computed
fields with
#[field_resolver], and the oneComplexObjectcaveat to watch for. - Relations resolve themselves — declare a SeaORM relation, get a typed GraphQL field with a batched loader and cursor pagination for free.
- Errors —
async_graphql::Error,ToProblem, and mappingServiceErrorto a GraphQL envelope.
All options
Section titled “All options”- Configuration —
GraphqlConfig, SDL emission, playground toggle, mount path. - Subscriptions —
#[subscription]over graphql-ws, gated at subscribe and filtered per item pushed. - The subscription socket — the handshake, what the upgrade lends the socket, and the bounds it holds.
- Error codes —
extensions.code, a problem’s type, and the field map keyed by the schema’s names. - Partial results — where a failed field’s
nulllands, and every error of one response. - Query limits — depth and complexity ceilings, and what a rejected query looks like.
- Field complexity — the page factor a relation scores, and the override any field takes.
- Federation — serve the schema as an Apollo Federation subgraph.
Reference
Section titled “Reference”crates/features/src/users/graphql/resolver.rs— a production-grade resolver with relations, dataloaders and authorization.posts/graphql/resolver.rsin the demo — thepublishPostmutation and draft/published status.crates/nest-rs-graphql/—#[resolver],#[query],#[mutation],#[field_resolver], schema composition.crates/nest-rs-seaorm/—#[expose]for an entity that becomes a GraphQL type and an OpenAPI schema from one declaration.
Going further
Section titled “Going further”- Security — bind the ability guard so resolvers run with an
authenticated principal and an ambient
Ability. - Database — the data layer the relation pages build on.
- Dataloaders —
#[dataloader]on a service method, for batched fetches beyond what relations give you. - WebSockets — the other realtime surface, for protocols that are message-shaped rather than schema-shaped.