Field resolvers
Custom computed and composed fields on a wire type with #[field_resolver] — and the one ComplexObject rule to know.
A #[field_resolver] adds a computed field to an output type. It runs
on every parent the client requested, gets injected services and
loaders the same way as #[query] / #[mutation], and slots into the
schema next to the type’s own fields with no extra wiring. Reach for
it when a property isn’t a stored column or auto-resolved relation — a
derived value, a cross-service shape, a non-default cardinality.
The smallest field resolver
Section titled “The smallest field resolver”The first argument after &self is the parent object; the return is the
field’s value.
use async_graphql::SimpleObject;use nest_rs::graphql::{operations, resolver};
#[derive(SimpleObject, Clone)]pub struct User { id: String, name: String,}
#[resolver]pub struct UsersResolver;
#[operations]impl UsersResolver { #[query] #[public] async fn user(&self, id: String) -> User { User { id, name: "Ada".into() } }
#[field_resolver] async fn display_name(&self, parent: &User) -> String { parent.name.to_uppercase() }}$ curl -sX POST http://localhost:3000/graphql -d \ '{"query":"{ user(id:\"1\") { name displayName } }"}'{"data":{"user":{"name":"Ada","displayName":"ADA"}}}The macro picks up &User as the parent type and grafts displayName
onto the User GraphQL object. No MergedObject, no ComplexObject
written by hand.
Reading the context, calling a service
Section titled “Reading the context, calling a service”Beyond parent, a #[field_resolver] accepts the same shapes a
#[query] does: ctx: &Context<'_>, plain argument types, and
#[inject]ed services on the host resolver.
use std::sync::Arc;use async_graphql::{Context, Result, SimpleObject};use nest_rs::graphql::{operations, resolver};
#[derive(SimpleObject, Clone)]pub struct User { id: String, name: String,}
#[resolver]pub struct UsersResolver { #[inject] profiles: Arc<crate::profiles::ProfilesService>,}
#[operations]impl UsersResolver { #[query] #[public] async fn user(&self, id: String) -> User { User { id, name: "Ada".into() } }
#[field_resolver] async fn avatar_url(&self, parent: &User) -> Result<Option<String>> { Ok(self.profiles.avatar_for(&parent.id).await?) }}If avatar_for does one DB call per parent, you have an N+1 — move
the lookup behind a #[dataloader] and read it through a
&DataLoader<L> parameter. See Dataloaders.
A Scoped<T> parameter reaches a request-scoped provider here as on a root
field, and an Ambient<T> parameter what the request’s guards attached, or its own
guards. A field resolver is no unit of its own — it runs once per parent row,
inside the root field that produced its parent — so it runs its resolver’s and
its own #[use_guards], and only the interceptors and exception filters
declared on it: never the app’s pool, nor the resolver’s interceptors, which
would run once per row.
Its parent is the wire row its root field built, judged for the caller, so a column
the caller’s grant withholds reads None there as on the wire. A parent judged for
someone else — a row kept from another request, a publisher’s — or one the caller may
not read refuses the field before it runs, INTERNAL or FORBIDDEN as the parent’s own
columns refuse, so nothing the resolver derives from it ships. A wire row it answers is
judged where it builds it, as a root field’s is,
and a column it reads off a whole Model and answers as its own value is its body’s
line (named there).
A caller with no credential reads nothing a grant guards there, whatever its root field
names (Public reads).
Its module is imported
Section titled “Its module is imported”A field resolver is grafted onto its parent’s GraphQL object when the crate compiles, so a schema serving the parent serves the field. The module gate still holds: a served field whose resolver the app does not reach refuses the boot, naming the import, rather than running outside every module the app declared.
a served field's resolver is one this app does not reach, so it would run outside every module the app imports: `User.avatarUrl` is resolved by `features::profiles::graphql::ProfilesResolver`: import `ProfilesGraphqlModule` into the module serving `User`The single-ComplexObject rule
Section titled “The single-ComplexObject rule”Concretely: an entity exposed with #[expose(name = "User", service = …)] that has a SeaORM relation field gets an auto-emitted
#[ComplexObject] for User carrying the relation’s field resolver.
Writing another #[field_resolver] with a parent: &User argument on
the resolver impl will not compile alongside it.
You have three honest ways out:
- Leave the relation unexposed (no
#[expose]) and own the full complex object on the resolver. The relation stays declared at the ORM level (the SQL join still works), it just no longer surfaces as a GraphQL field automatically. Write your#[field_resolver]for whatever shape you actually want — cursor connection, filtered subset, custom cardinality. - Move the custom logic to a different wire type. Keep
Userfor the auto-resolved relation surface, and expose a siblingUserProfileshape (orUserConnection, etc.) carrying the custom fields. - Leave it to the relation. If the custom field is structurally
identical to what the auto-emitted loader gives you, drop the
#[field_resolver]and read Relations instead.
Own a relation yourself
Section titled “Own a relation yourself”Leaving a relation field unexposed (no #[expose]) keeps auto-emission
off for that field only. The relation stays declared at the ORM level
(SeaORM still knows about it), and you can write a hand-rolled
#[field_resolver] if you need a shape the auto-emitted one does not
give you — a filtered or sorted subset, extra edge fields, a projection.
Cursor pagination is not on that list any more: the auto-emitted
field already is a connection.
#[expose(name = "Org", service = …, graphql, complex)]#[sea_orm::model]pub struct Model { #[expose] pub id: Uuid, #[expose] pub name: String,
// No #[expose] => not auto-resolved; own it with a #[field_resolver]. #[sea_orm(has_many)] pub users: HasMany<crate::users::Entity>,}A custom shape: a filtered relation
Section titled “A custom shape: a filtered relation”When the unexposed relation opens the slot, write the replacement on the resolver.
With no exposed relation left on the type, complex is what serves its
#[field_resolver]s:
use std::sync::Arc;
use nest_rs::graphql::async_graphql::Result;use nest_rs::graphql::{operations, resolver};
use crate::orgs::Org;use crate::users::{User, UsersService};
#[resolver]pub struct OrgsResolver { #[inject] svc: Arc<UsersService>,}
#[operations]impl OrgsResolver { #[field_resolver] async fn admins(&self, parent: &Org) -> Result<Vec<User>> { Ok(self.svc.admins_in_org(parent.id).await?) }}The filter, the service method, and the User wire DTO all stay where
they belong — the resolver only translates between the two.
Why the macro picks the parent
Section titled “Why the macro picks the parent”#[field_resolver] infers the parent type from the first argument after the
receiver, by reference, and a ctx: &Context<'_> comes after it. Every other argument becomes a
GraphQL input or, when it’s a reference, comes from the container — a
&DataLoader<L> from the request.
#[field_resolver]async fn display_name( &self, parent: &User, // ← parent type, inferred ctx: &Context<'_>, // optional upper: bool, // GraphQL argument) -> String { if upper { parent.name.to_uppercase() } else { parent.name.clone() }}type User { displayName(upper: Boolean!): String!}Going further
Section titled “Going further”- Relations — auto-resolved fields for
belongs-to / has-many; this is where the
ComplexObjectrule matters most. - Dataloaders — batch the per-parent DB
call a
#[field_resolver]would otherwise do N times. - Errors — how a
Result<T, ServiceError>lands on the wire.