RapidGo
No results found

GraphQL

Built-in GraphQL server with GraphiQL playground.

RapidGo includes a GraphQL server built on graphql-go with a Gin handler and GraphiQL playground.

Defining a Schema

import gql "github.com/graphql-go/graphql"

var userType = gql.NewObject(gql.ObjectConfig{
    Name: "User",
    Fields: gql.Fields{
        "id":    &gql.Field{Type: gql.Int},
        "name":  &gql.Field{Type: gql.String},
        "email": &gql.Field{Type: gql.String},
    },
})

var queryType = gql.NewObject(gql.ObjectConfig{
    Name: "Query",
    Fields: gql.Fields{
        "user": &gql.Field{
            Type: userType,
            Args: gql.FieldConfigArgument{
                "id": &gql.ArgumentConfig{Type: gql.NewNonNull(gql.Int)},
            },
            Resolve: func(p gql.ResolveParams) (interface{}, error) {
                id := p.Args["id"].(int)
                // Fetch user from database...
                return user, nil
            },
        },
    },
})

schema, _ := gql.NewSchema(gql.SchemaConfig{Query: queryType})

Registering Routes

import "github.com/RAiWorks/RapidGo/v2/core/graphql"

// GraphQL endpoint (POST and GET)
r.Post("/graphql", graphql.Handler(schema))
r.Get("/graphql", graphql.Handler(schema))

// GraphiQL playground
r.Get("/graphiql", graphql.Playground("My API", "/graphql"))

Request Format

POST (JSON body)

{
    "query": "{ user(id: 42) { name email } }",
    "variables": {},
    "operationName": ""
}

GET (query parameters)

/graphql?query={ user(id: 42) { name email } }

Accessing Gin Context in Resolvers

Resolve: func(p gql.ResolveParams) (interface{}, error) {
    ginCtx, ok := graphql.FromContext(p.Context)
    if ok {
        userID := ginCtx.GetUint("user_id")
        // Use authenticated user context...
    }
    return result, nil
},