Skip to content

Queries and mutations

Top-level operations as plain async methods — typed arguments, typed returns, the wire shape that follows.

Every top-level operation is an async method on an #[operations] impl block, tagged with #[query] or #[mutation]. An operation that answers more than once is a #[subscription] and follows the same shape. The method signature is the wire contract: parameters become GraphQL arguments, the return type becomes the response shape, and an error short-circuits with a GraphQL error envelope. There is no separate “schema definition” step — the registry composes one root Query and one root Mutation from every decorated method in the running app.

crates/features/src/users/graphql/resolver.rs
use nest_rs::graphql::{operations, resolver};
#[resolver]
pub struct UsersResolver;
#[operations]
impl UsersResolver {
#[query]
#[public]
async fn user_count(&self) -> i32 {
42
}
}

#[public] is the operation’s access posture: every #[query] / #[mutation] declares one of three, and a method with none does not compile:

  • #[public] — a caller with no credential is admitted, and the operation reads nothing a grant guards.
  • #[authorize(Action, Subject)] — ability gate, and reads under the caller’s ability, each wire row judged for that caller, for a caller a principal backs.
  • #[public(Action, Subject)] — the same gate and reads on the ability a caller with no credential has: what a visitor reads.

The posture is always one of these visible attributes — a parameter type is never a posture. A bound mutation acts on a row named by id: it still carries #[authorize(Action, Subject)], then loads the Authorized<A, E> subject in its body. See Database / Bound mutations.

The toy examples on this page are #[public]; the service-backed ones on Services and context carry #[authorize].

On the wire this reads as:

Terminal window
$ curl -sX POST http://localhost:3000/graphql \
-H 'Content-Type: application/json' \
-d '{"query":"{ userCount }"}'
{"data":{"userCount":42}}

The method name is camelCased by async-graphql’s own rule: a new word starts after each _ and after a digit, and a capital after a lowercase letter is kept — user_count is userCount, get_2fa is get2Fa, userID stays userID. The framework states that name on the field itself, so the name a duplicate is checked under is the name served: two methods the rule reads as one field (a1_b and a_1b are both a1B) are a compile error rather than one body answering for the other. #[graphql(name = "…")] overrides it. Primitive returns map to their GraphQL scalar (i32 → Int, String → String, bool → Boolean).

Add typed parameters and they become required GraphQL arguments; Option<T> makes one nullable.

crates/features/src/users/graphql/resolver.rs
#[operations]
impl UsersResolver {
#[query]
#[public]
async fn label(&self, id: String, locale: Option<String>) -> String {
let locale = locale.as_deref().unwrap_or("en");
format!("user {id} in {locale}")
}
}
Terminal window
$ curl -sX POST http://localhost:3000/graphql -d \
'{"query":"{ label(id: \"42\", locale: \"fr\") }"}'
{"data":{"label":"user 42 in fr"}}

Validation happens at deserialization: a missing required arg returns a parse error, a wrong scalar returns a coercion error. Both come back with no resolver call.

Beyond shape checks, an argument whose type declares validator rules is held to them, and a custom transform binds a pipe per parameter, Piped<P>, whose input the SDL shows. A rejection surfaces in the response’s errors, under extensions.code: "INVALID_ARGUMENT" — the resolver body never runs.

crates/features/src/users/graphql/resolver.rs
use async_graphql::InputObject;
use nest_rs::core::input;
#[derive(InputObject)]
#[input]
pub struct NameInput {
#[validate(length(min = 1))]
name: String,
}
#[query]
#[public]
async fn named(&self, input: NameInput) -> nest_rs::graphql::async_graphql::Result<String> {
Ok(input.name)
}

For anything beyond a scalar, define a SimpleObject (output) and optionally an InputObject (input):

crates/features/src/users/graphql/resolver.rs
use async_graphql::SimpleObject;
use nest_rs::graphql::{operations, resolver};
#[derive(SimpleObject)]
pub struct User {
id: String,
name: String,
email: String,
}
#[resolver]
pub struct UsersResolver;
#[operations]
impl UsersResolver {
#[query]
#[public]
async fn user(&self, id: String) -> User {
User { id, name: "Ada".into(), email: "ada@example.com".into() }
}
}

Every field of User is queryable independently:

Terminal window
$ curl -sX POST http://localhost:3000/graphql -d \
'{"query":"{ user(id:\"1\") { name email } }"}'
{"data":{"user":{"name":"Ada","email":"ada@example.com"}}}

When you #[expose] an entity, the wire DTO is generated for you and plugs into this slot directly — no second SimpleObject to maintain (Relations).

#[mutation] is the same shape as #[query]; the marker swaps the operation root.

crates/features/src/users/graphql/resolver.rs
use async_graphql::{InputObject, SimpleObject};
use nest_rs::graphql::{operations, resolver};
#[derive(InputObject)]
pub struct NewUserInput {
name: String,
email: String,
}
#[derive(SimpleObject)]
pub struct User {
id: String,
name: String,
email: String,
}
#[resolver]
pub struct UsersResolver;
#[operations]
impl UsersResolver {
#[mutation]
#[public]
async fn create_user(&self, input: NewUserInput) -> User {
User {
id: "u-001".into(),
name: input.name,
email: input.email,
}
}
}
Terminal window
$ curl -sX POST http://localhost:3000/graphql -d \
'{"query":"mutation { createUser(input: {name: \"Ada\", email: \"ada@example.com\"}) { id name } }"}'
{"data":{"createUser":{"id":"u-001","name":"Ada"}}}

InputObject makes a struct usable as an argument type; SimpleObject makes one usable as a return type. Both come from async-graphql (re-exported by nest-rs-graphql).

Each operation runs as a unit of work of its own: a query on the pool, a mutation in one transaction. Its root fields resolve one after the other, each in a savepoint, so a field that answers null for an error rolls back what it wrote — and drops the events it emitted — while the other fields of the operation commit; a Non-Null one’s null reaches data, and the whole operation rolls back with it (GraphQL: one unit per operation).

A variable reads what the request sent, or its default when it sent none, as much in @skip and @include as in an argument. With no variables sent, this selects body:

query Post($full: Boolean = true) {
post { title body @include(if: $full) }
}

A required variable the request leaves out — $id: ID!, no default — refuses the whole operation once validation passed, and nothing runs: data: null and one INVALID_ARGUMENT error, Variable "$id" of required type "ID!" was not provided. So does one it sends null where the variable’s type says !, even into an argument that would take a null: Variable "$id" of non-null type "ID!" must not be null., or, inside a list, Variable "$ids" of type "[ID!]" must not hold null at "ids[1]". A variable pipe runs first, so a directive reads what it made of a variable; a default is the document’s own, and no pipe is handed it.

A resolver method may return T or async_graphql::Result<T> — both work, but a Result lets you short-circuit with a typed GraphQL error:

crates/features/src/users/graphql/resolver.rs
use nest_rs::graphql::async_graphql::{Error, Result};
#[query]
#[public]
async fn user(&self, id: String) -> Result<User> {
if id.is_empty() {
return Err(Error::new("id must not be empty"));
}
Ok(User { id, name: "Ada".into(), email: "ada@example.com".into() })
}

The full error story (extensions, codes, mapping ServiceError) is on its own page: Errors.

A resolver reaches its data through the service it injects, svc: Arc<UsersService>, each operation declaring the posture it is gated by. What the request carries beyond the document — the caller a guard attached (Ambient<T>), a request-scoped provider (Scoped<T>), a batch loader (&DataLoader<L>) — is a parameter, as on a route, and no schema argument. Services and context shows both.

  • Field resolvers — add computed or composed fields to an output type.
  • Relations — let #[expose] write the entity-to-entity wire shape for you.
  • Errors — the full mapping from service errors to a GraphQL envelope.