Skip to main content

graphql

Attribute Macro graphql 

Source
#[graphql]
Expand description

Generate GraphQL schema from an impl block using async-graphql.

Methods are automatically classified as Queries or Mutations based on naming:

  • Queries: get_*, list_*, find_*, search_*, fetch_*, query_*
  • Mutations: everything else (create, update, delete, etc.)

§Basic Usage

use server_less::graphql;

#[graphql]
impl UserService {
    // Query: returns single user
    async fn get_user(&self, id: String) -> Option<User> {
        // ...
    }

    // Query: returns list of users
    async fn list_users(&self) -> Vec<User> {
        // ...
    }

    // Mutation: creates new user
    async fn create_user(&self, name: String, email: String) -> User {
        // ...
    }
}

§Type Mappings

  • String, i32, bool, etc. → GraphQL scalars
  • Option<T> → nullable GraphQL field
  • Vec<T> → GraphQL list [T]
  • Custom structs → GraphQL objects (must derive SimpleObject)
use async_graphql::SimpleObject;

#[derive(SimpleObject)]
struct User {
    id: String,
    name: String,
    email: Option<String>,  // Nullable field
}

#[graphql]
impl UserService {
    async fn get_user(&self, id: String) -> Option<User> {
        // Returns User object with proper GraphQL schema
    }

    async fn list_users(&self) -> Vec<User> {
        // Returns [User] in GraphQL
    }
}

§GraphQL Queries

# Query single user
query {
  getUser(id: "123") {
    id
    name
    email
  }
}

# List all users
query {
  listUsers {
    id
    name
  }
}

# Mutation
mutation {
  createUser(name: "Alice", email: "alice@example.com") {
    id
    name
  }
}

§Custom Scalars

Common custom scalar types are automatically supported:

use chrono::{DateTime, Utc};
use uuid::Uuid;

#[graphql]
impl EventService {
    // UUID parameter
    async fn get_event(&self, event_id: Uuid) -> Option<Event> { /* ... */ }

    // DateTime parameter
    async fn list_events(&self, since: DateTime<Utc>) -> Vec<Event> { /* ... */ }

    // JSON parameter
    async fn search_events(&self, filter: serde_json::Value) -> Vec<Event> { /* ... */ }
}

Supported custom scalars:

  • chrono::DateTime<Utc> → DateTime
  • uuid::Uuid → UUID
  • url::Url → Url
  • serde_json::Value → JSON

§Generated Methods

  • graphql_schema() -> Schema - async-graphql Schema
  • graphql_router() -> axum::Router - Router with /graphql endpoint
  • graphql_sdl() -> String - Schema Definition Language string