Mirror on GraphQL
A UsersResolver alongside the controller, queries and mutations on one impl, auto-resolved relations, SDL emitted as a side effect of the dev run.
The reference feature gains a GraphQL adapter — a single resolver
struct, two operations, zero changes to the service. By the end of this
page, POST /graphql answers { users { id name } } against the same
authn, the same ability, the same Postgres rows, and the User.org
field auto-resolves through a dataloader without an N+1.
The resolver
Section titled “The resolver”A resolver is a struct decorated with #[resolver], with operations on the
impl block.
nest-rs-graphql
brings schema discovery, dataloader registration and the endpoint’s guards;
the schema model itself is async-graphql’s.
use std::sync::Arc;
use nest_rs::graphql::{crud, resolver};
use crate::authz::AuthzGuard;use crate::users::UsersService;
#[resolver]#[use_guards(AuthzGuard)]pub struct UsersResolver { #[inject] svc: Arc<UsersService>,}
#[crud(service = UsersService)]impl UsersResolver {}#[crud] generates users, user, create_user, update_user and
delete_user — named for the resolver’s resource, UsersResolver without
Resolver, made singular — each typed off UsersService and its entity’s
#[expose], and each declaring #[authorize(Action, Entity)] on the
service’s entity. The
generated create_user needs nothing from you to land in the caller’s org:
the Create grant pins org_id, and the create fills it from there.
#[authorize(Action, Entity)] is each operation’s access posture:
the macro emits the class-level gate before your body runs, and each
User::from(&row) judges its row for the caller — you never call
authorize or a masking function by hand. A deliberately open operation declares #[public]
instead.
Symmetry with the HTTP controller is intentional — the same service, inputs, policy, posture attribute and principal’s parameter:
| HTTP | GraphQL | Job |
|---|---|---|
#[authorize(Create, users::Entity)] attribute | #[authorize(Create, users::Entity)] attribute | Refuse the operation if the ability disallows it and read under the caller’s ability |
#[authorize(Read, bind = UsersService)] attribute, an Authorized<Read, UserEntity> parameter | the same attribute and parameter, the id argument synthesised | Load the row through the service, refuse it on a denied ability |
Ambient<Claims> parameter | Ambient<Claims> parameter, no argument of the schema | Read the principal the endpoint’s guards attached |
The resolver names AuthzGuard alone because /graphql authenticates at its
request, before any field runs: AuthzGraphqlModule, imported below, declares
EndpointGuards<GraphqlView, (AuthnGuard, AuthzGuard)> for it. AuthnGuard
reads a bearer token off an HTTP request (GuardFor<HttpView> alone), so
binding it on a resolver is a compile error; on a field, AuthzGuard refuses
one no ability reached — a request that did not authenticate.
The GraphQL module
Section titled “The GraphQL module”The adapter imports the port (UsersModule), the authz module
(AuthzGraphqlModule) and the org and post ports, whose services host the
auto-emitted loaders — the entity exposes relations, a belongs_to org (next
section) and a has_many of posts. The resolver brings GraphqlModule, the
endpoint its operations are served on:
use nest_rs::core::module;
use super::resolver::UsersResolver;use crate::authz::graphql::AuthzGraphqlModule;use crate::orgs::OrgsModule;use crate::posts::PostsModule;use crate::users::UsersModule;
#[module( imports = [UsersModule, OrgsModule, PostsModule, AuthzGraphqlModule], providers = [UsersResolver],)]pub struct UsersGraphqlModule;The folder’s mod.rs exports the module alone, as the HTTP adapter’s does,
and users/mod.rs re-exports it beside UsersHttpModule.
Wire the adapter
Section titled “Wire the adapter”The app root imports UsersGraphqlModule, whose resolver brings the endpoint
with it: GraphqlModule mounts once however many resolvers bring it. The
adapter imports AuthzGraphqlModule, which declares the guards /graphql’s
request runs, so the root lists the adapter alone.
GraphqlModule mounts POST /graphql on the HTTP transport it imports.
GET /graphql serves the playground, and introspection answers, under a
declared development or test profile alone — nestrs run dev declares
development — so a deployment exposes no interactive console and
GET /graphql answers 405 (see
GraphQL configuration).
The schema itself is composed from every #[resolver] the access graph
reaches — no central queries = [...] list to keep in sync.
Run a query
Section titled “Run a query”$ curl -s -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' \ -d '{"query":"{ users { id name email } }"}' \ http://localhost:3002/graphql{"data":{"users":[{"id":"018f…","name":"Ada","email":"ada@acme.test"}]}}The ambient ability runs on the query — a plain user gets the same
filter as the HTTP GET /users, and the same masking: the entity declares
email nullable, so it is String in the schema and reads null for a
caller whose grant withholds it, refusing nothing. Same policy, two transports.
Relations resolve themselves
Section titled “Relations resolve themselves”If the entity declared a belongs_to field — say org pointing at
OrgsEntity — adding it to the SeaORM model is enough. The macro
emits the Org PK loader on OrgsService and a #[ComplexObject]
field resolver on the wire DTO. No #[field_resolver] to write, no
#[dataloader] to call by hand.
#[expose( name = "User", service = super::super::service::UsersService, graphql, // …)]#[sea_orm::model]#[derive(Clone, Debug, DeriveEntityModel)]// …pub struct Model { // … id, org_id, name, email — each carrying #[expose] #[sea_orm(belongs_to, from = "org_id", to = "id")] #[expose] pub org: HasOne<crate::orgs::Entity>, // …}A nested query batches through the loader rather than issuing one query per parent:
$ curl -s -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' \ -d '{"query":"{ users { id name org { id } } }"}' \ http://localhost:3002/graphql{"data":{"users":[ {"id":"018f…","name":"Ada","org":{"id":"018e…"}}]}}The User.org resolver runs through Repo::scoped(Action::Read), so
an out-of-scope org never surfaces — the row-level filter applies to
each batched query the loader issues.
Emit the SDL
Section titled “Emit the SDL”For tooling, commit a schema.graphql alongside the binary. The
framework writes one beside the app’s Cargo.toml as a side effect of every
development run — the profile opens <PREFIX>_GRAPHQL__EMIT, and nothing
else does:
$ nestrs run dev apiINFO nest_rs::graphql: wrote GraphQL SDL path=/home/dev/blog/apps/api/schema.graphql
$ grep -A7 '^type Query' apps/api/schema.graphqltype Query { org(id: String!): Org orgs(after: String, first: Int): [Org!]! post(id: String!): Post posts(after: String, first: Int): [Post!]! user(id: String!): User users(after: String, first: Int): [User!]!}Commit the file and assert on it if you want a drift gate.
Now mirror your own blog
Section titled “Now mirror your own blog”posts already has the entity, the service and the policy — a resolver is one
more adapter over them:
$ nestrs g graphql posts --app blogThat writes crates/features/src/posts/graphql/{resolver.rs,module.rs,mod.rs}
— the #[crud] resolver, and the module listing it — and the
GraphQL authz module under authz/graphql/, flags the entity
#[expose(graphql)], and wires PostsGraphqlModule into blog. Restart, and
POST /graphql, carrying the same bearer your curls do, answers through the
same ability your HTTP routes go through — a plain token reads, an admin’s
writes:
$ curl -s -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' \ -d '{"query":"{ posts { id title } }"}' \ http://localhost:3001/graphql{"data":{"posts":[{"id":"019f…","title":"Hello"}]}}Going further
Section titled “Going further”- Tutorial overview — recap the full
postsbuild, start to finish. - GraphQL — the reference page for resolvers, dataloaders, and the endpoint’s guards.
- Publish — the reference workspace where this multi-transport feature ships.