gqlt

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2025 License: MIT Imports: 14 Imported by: 0

README

gqlt

A powerful GraphQL CLI tool and Go library for querying GraphQL APIs, schema introspection, and testing. Perfect for automation, seeding, testing, and AI agents.

Features

  • GraphQL Operations: Execute queries, mutations, and subscriptions
  • Schema Introspection: Analyze and explore GraphQL schemas
  • File Uploads: Support for multipart/form-data file uploads
  • Authentication: Bearer tokens, Basic auth, and API keys
  • Configuration Management: Multiple named configurations
  • AI-Friendly: Structured output, machine-readable errors, quiet mode
  • Testing Utilities: Mock servers, test helpers, and assertions
  • Library Support: Use as a Go library in your applications

Installation

go install github.com/kluzzebass/gqlt@latest

CLI Usage

Basic Query
# Simple query
gqlt run --query '{ users { id name } }' --url https://api.example.com/graphql

# Query with variables
gqlt run --query 'query GetUser($id: ID!) { user(id: $id) { name email } }' \
  --variables '{"id": "123"}' \
  --url https://api.example.com/graphql

# Query from file
gqlt run --query-file query.graphql --url https://api.example.com/graphql
Configuration Management
# Initialize configuration
gqlt config init

# Create a new configuration
gqlt config create production --endpoint https://api.production.com/graphql

# Switch to a configuration
gqlt config use production

# List configurations
gqlt config list
Schema Introspection
# Introspect and save schema
gqlt introspect --url https://api.example.com/graphql

# Describe schema types
gqlt describe --url https://api.example.com/graphql
Validation
# Validate query against schema
gqlt validate query --query '{ users { id } }' --url https://api.example.com/graphql

# Validate configuration
gqlt validate config

# Validate schema
gqlt validate schema --url https://api.example.com/graphql

Library Usage

Basic Client
package main

import (
    "fmt"
    "log"
    
    "github.com/kluzzebass/gqlt"
)

func main() {
    // Create client
    client := gqlt.NewClient("https://api.example.com/graphql", nil)
    
    // Execute query
    response, err := client.Execute(
        `query GetUsers { users { id name email } }`,
        nil,
        "GetUsers",
    )
    if err != nil {
        log.Fatal(err)
    }
    
    // Check for errors
    if len(response.Errors) > 0 {
        fmt.Printf("GraphQL errors: %v\n", response.Errors)
    }
    
    // Use response data
    fmt.Printf("Response: %+v\n", response.Data)
}
Authentication
// Bearer token authentication
client := gqlt.NewClient("https://api.example.com/graphql", nil)
client.SetHeaders(map[string]string{
    "Authorization": "Bearer your-token",
})

// Basic authentication
client.SetAuth("username", "password")

// API key authentication
client.SetHeaders(map[string]string{
    "X-API-Key": "your-api-key",
})
Schema Introspection
// Create introspection client
client := gqlt.NewClient("https://api.example.com/graphql", nil)
introspect := gqlt.NewIntrospect(client)

// Introspect schema
schema, err := introspect.IntrospectSchema()
if err != nil {
    log.Fatal(err)
}

// Analyze schema
analyzer, err := gqlt.NewAnalyzer(schema)
if err != nil {
    log.Fatal(err)
}

summary, err := analyzer.GetSummary()
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Schema has %d types\n", summary.TotalTypes)
fmt.Printf("Query type: %s\n", summary.QueryType)
Configuration Management
// Load configuration
config, err := gqlt.Load("/path/to/config")
if err != nil {
    log.Fatal(err)
}

// Get current configuration
current := config.GetCurrent()
fmt.Printf("Current endpoint: %s\n", current.Endpoint)

// Create new configuration
config.Configs["production"] = gqlt.ConfigEntry{
    Endpoint: "https://api.production.com/graphql",
    Headers: map[string]string{
        "Authorization": "Bearer prod-token",
    },
}

// Save configuration
err = config.Save("/path/to/config")
if err != nil {
    log.Fatal(err)
}
File Uploads
// Execute mutation with file upload
response, err := client.ExecuteWithFiles(
    `mutation UploadFile($file: Upload!) { uploadFile(file: $file) { id } }`,
    map[string]interface{}{"file": nil},
    "UploadFile",
    map[string]string{"file": "/path/to/file.jpg"},
)
Testing with Mock Server
package main

import (
    "testing"
    "github.com/kluzzebass/gqlt"
)

func TestGraphQL(t *testing.T) {
    // Create mock server
    mock := gqlt.NewMockGraphQLServer()
    defer mock.Close()
    
    // Add handler
    mock.AddHandler("GetUsers", func(response *gqlt.Response) {
        response.Data = map[string]interface{}{
            "users": []map[string]interface{}{
                {"id": "1", "name": "John Doe"},
            },
        }
    })
    
    // Test with client
    client := gqlt.NewClient(mock.URL(), nil)
    response, err := client.Execute(
        `query GetUsers { users { id name } }`,
        nil,
        "GetUsers",
    )
    
    if err != nil {
        t.Fatalf("Query failed: %v", err)
    }
    
    // Verify response
    if len(response.Errors) > 0 {
        t.Errorf("Unexpected errors: %v", response.Errors)
    }
}
Test Utilities
func TestWithHelper(t *testing.T) {
    helper := gqlt.NewGraphQLTestHelper(t, "https://api.example.com/graphql")
    
    // Set authentication
    helper.SetAuth("bearer", map[string]string{
        "token": "your-token",
    })
    
    // Execute query
    response := helper.ExecuteQuery("{ users { id name } }", nil, "")
    
    // Use assertions
    helper.AssertNoErrors(response)
    helper.AssertFieldExists(response, "users")
    helper.AssertArrayLength(response, "users", 2)
}

Output Formats

gqlt supports multiple output formats for different use cases:

  • json: Formatted JSON output (default)
  • pretty: Colorized JSON output
  • raw: Compact JSON output
  • table: Human-readable table format
  • yaml: YAML format
# Use different output formats
gqlt run --query '{ users { id } }' --format table
gqlt run --query '{ users { id } }' --format yaml
gqlt run --query '{ users { id } }' --format raw

AI-Friendly Features

gqlt is designed to work well with AI agents and automation:

  • Structured Output: All commands support --format json for machine-readable output
  • Error Codes: Standardized error codes for programmatic handling
  • Quiet Mode: --quiet flag for automation scenarios
  • Validation Commands: Structured validation results
  • Configuration: Self-documenting configuration system
# AI-friendly usage
gqlt run --query '{ users { id } }' --format json --quiet
gqlt validate query --query '{ users { id } }' --format json

Examples

See the examples/ directory for comprehensive examples including:

  • Basic GraphQL operations
  • Authentication patterns
  • Schema introspection
  • Configuration management
  • Testing utilities
  • Mock servers
  • Integration tests

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

MIT License - see LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	// Configuration errors
	ErrorCodeConfigLoad     = "CONFIG_LOAD_ERROR"
	ErrorCodeConfigNotFound = "CONFIG_NOT_FOUND"
	ErrorCodeConfigCreate   = "CONFIG_CREATE_ERROR"
	ErrorCodeConfigSave     = "CONFIG_SAVE_ERROR"
	ErrorCodeConfigDelete   = "CONFIG_DELETE_ERROR"
	ErrorCodeConfigValidate = "CONFIG_VALIDATE_ERROR"

	// Input validation errors
	ErrorCodeInputValidation = "INPUT_VALIDATION_ERROR"
	ErrorCodeQueryLoad       = "QUERY_LOAD_ERROR"
	ErrorCodeVariablesLoad   = "VARIABLES_LOAD_ERROR"
	ErrorCodeFilesParse      = "FILES_PARSE_ERROR"
	ErrorCodeFilesListParse  = "FILES_LIST_PARSE_ERROR"

	// GraphQL execution errors
	ErrorCodeGraphQLExecution = "GRAPHQL_EXECUTION_ERROR"
	ErrorCodeGraphQLErrors    = "GRAPHQL_ERRORS"
	ErrorCodeNetworkError     = "NETWORK_ERROR"
	ErrorCodeAuthError        = "AUTH_ERROR"

	// Schema errors
	ErrorCodeSchemaLoad       = "SCHEMA_LOAD_ERROR"
	ErrorCodeSchemaIntrospect = "SCHEMA_INTROSPECT_ERROR"
	ErrorCodeSchemaSave       = "SCHEMA_SAVE_ERROR"

	// System errors
	ErrorCodeSystemError      = "SYSTEM_ERROR"
	ErrorCodeFileNotFound     = "FILE_NOT_FOUND"
	ErrorCodePermissionDenied = "PERMISSION_DENIED"
)

Common error codes for AI agents

Variables

This section is empty.

Functions

func GetAvailableFormatters

func GetAvailableFormatters() []string

GetAvailableFormatters returns all available formatter names

func GetConfigPath

func GetConfigPath() string

GetConfigPath returns the path to the main configuration file. This is typically config.json in the default configuration directory.

func GetConfigPathForDir

func GetConfigPathForDir(configDir string) string

GetConfigPathForDir returns the path to the configuration file in a specific directory.

func GetDefaultPath

func GetDefaultPath() string

Public path functions GetDefaultPath returns the default configuration directory path for the current OS. On Linux: ~/.config/gqlt On macOS: ~/Library/Application Support/gqlt On Windows: %APPDATA%/gqlt

func GetGraphQLSchemaPathForConfigInDir

func GetGraphQLSchemaPathForConfigInDir(configName, configDir string) string

GetGraphQLSchemaPathForConfigInDir returns the path to the GraphQL SDL schema file for a specific configuration in a specific directory.

func GetJSONSchemaPathForConfigInDir

func GetJSONSchemaPathForConfigInDir(configName, configDir string) string

GetJSONSchemaPathForConfigInDir returns the path to the JSON schema file for a specific configuration in a specific directory.

func GetSchemaPath

func GetSchemaPath() string

GetSchemaPath returns the path to the default schema file. This is typically schema.json in the default configuration directory.

func GetSchemaPathForConfig

func GetSchemaPathForConfig(configName string) string

GetSchemaPathForConfig returns the path to the schema file for a specific configuration. This is typically schemas/{configName}.json in the default configuration directory.

func GetSchemaPathForConfigInDir

func GetSchemaPathForConfigInDir(configName, configDir string) string

GetSchemaPathForConfigInDir returns the path to the schema file for a specific configuration in a specific directory.

func GetSchemasDir

func GetSchemasDir() string

GetSchemasDir returns the path to the schemas directory. This is typically schemas/ in the default configuration directory.

func RegisterFormatter

func RegisterFormatter(name string, factory FormatterFactory)

RegisterFormatter registers a custom formatter with the default registry

func SaveGraphQLSchema

func SaveGraphQLSchema(schema *Response, filePath string) error

SaveGraphQLSchema saves the schema as GraphQL SDL

func SaveSchema

func SaveSchema(result *Response, path string) error

SaveSchema saves schema to a single file

func SaveSchemaDual

func SaveSchemaDual(result *Response, configName, configDir string) error

SaveSchemaDual saves schema in both JSON and GraphQL formats

func SchemaExists

func SchemaExists(path string) bool

SchemaExists checks if a schema file exists

func Version

func Version() string

Version returns the current version of the gqlt library

Types

type Analyzer

type Analyzer struct {
	// contains filtered or unexported fields
}

Analyzer handles GraphQL schema analysis and provides utilities for exploring and understanding GraphQL schemas. It can extract type information, field details, and generate human-readable descriptions of schema elements.

func LoadAnalyzerFromFile

func LoadAnalyzerFromFile(filePath string) (*Analyzer, error)

LoadAnalyzerFromFile creates a new schema analyzer by loading a schema from a JSON file. The file should contain a GraphQL introspection response in JSON format.

Example:

analyzer, err := gqlt.LoadAnalyzerFromFile("schema.json")
if err != nil {
    log.Fatal(err)
}

func NewAnalyzer

func NewAnalyzer(schema *Response) (*Analyzer, error)

NewAnalyzer creates a new schema analyzer from a GraphQL introspection response. The schema parameter should be the result of a GraphQL introspection query.

Example:

analyzer, err := gqlt.NewAnalyzer(introspectionResponse)
if err != nil {
    log.Fatal(err)
}

func (*Analyzer) FindField

func (a *Analyzer) FindField(rootType, fieldName string) (*FieldDescription, error)

FindField finds a field in a root type

func (*Analyzer) FindType

func (a *Analyzer) FindType(typeName string) (*TypeDescription, error)

FindType finds a type by name

func (*Analyzer) GetFieldDescription

func (a *Analyzer) GetFieldDescription(rootType string, fieldObj map[string]interface{}) (*FieldDescription, error)

GetFieldDescription gets a field description

func (*Analyzer) GetSummary

func (a *Analyzer) GetSummary() (*Summary, error)

GetSummary returns a summary of the schema

func (*Analyzer) GetTypeDescription

func (a *Analyzer) GetTypeDescription(typeName string) (*TypeDescription, error)

GetTypeDescription gets a type description by name

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents a GraphQL client that can execute queries, mutations, and subscriptions against a GraphQL endpoint. It handles authentication, headers, and HTTP communication.

func NewClient

func NewClient(endpoint string, headers map[string]string) *Client

NewClient creates a new GraphQL client for the specified endpoint. The headers parameter can be nil or contain additional HTTP headers to send with requests.

Example:

client := gqlt.NewClient("https://api.example.com/graphql", map[string]string{
    "Authorization": "Bearer token",
})

func (*Client) Execute

func (c *Client) Execute(query string, variables map[string]interface{}, operationName string) (*Response, error)

Execute executes a GraphQL query, mutation, or subscription against the configured endpoint. The query parameter contains the GraphQL operation string, variables contains any variables to be passed to the operation, and operationName specifies which operation to execute (useful when the query contains multiple operations).

Example:

response, err := client.Execute(
    `query GetUser($id: ID!) { user(id: $id) { name email } }`,
    map[string]interface{}{"id": "123"},
    "GetUser",
)

func (*Client) ExecuteWithFiles

func (c *Client) ExecuteWithFiles(query string, variables map[string]interface{}, operationName string, files map[string]string) (*Response, error)

ExecuteWithFiles executes a GraphQL operation with file uploads using multipart/form-data. This method is used for GraphQL operations that require file uploads, such as mutations with Upload scalar types. The files parameter maps field names to file paths.

Example:

response, err := client.ExecuteWithFiles(
    `mutation UploadFile($file: Upload!) { uploadFile(file: $file) { id } }`,
    map[string]interface{}{"file": nil}, // File will be provided via files parameter
    "UploadFile",
    map[string]string{"file": "/path/to/file.jpg"},
)

func (*Client) Introspect

func (c *Client) Introspect() (*Response, error)

Introspect performs GraphQL introspection to get the schema

func (*Client) SetAuth

func (c *Client) SetAuth(username, password string)

SetAuth sets basic authentication for the client using the provided username and password. This will add an Authorization header with Basic authentication to all requests.

Example:

client.SetAuth("username", "password")

func (*Client) SetHeaders

func (c *Client) SetHeaders(headers map[string]string)

SetHeaders sets additional HTTP headers for the client. These headers will be sent with all subsequent requests.

Example:

client.SetHeaders(map[string]string{
    "Authorization": "Bearer token",
    "X-Custom-Header": "value",
})

type Config

type Config struct {
	Current string                 `json:"current"` // active config name (defaults to "default")
	Configs map[string]ConfigEntry `json:"configs"` // named configurations
}

Config represents the main configuration structure that manages multiple named configurations. It allows switching between different GraphQL endpoints and their associated settings.

func GetDefaultConfig

func GetDefaultConfig() *Config

GetDefaultConfig returns a default configuration

func Load

func Load(configDir string) (*Config, error)

Load reads a configuration file from the specified config directory. If configDir is empty, it searches in standard locations (current directory, then default path). Returns a Config struct with the loaded configuration or an error if loading fails.

Example:

config, err := gqlt.Load("/path/to/config")
if err != nil {
    log.Fatal(err)
}

func (*Config) Create

func (c *Config) Create(name string) error

Create creates a new configuration entry

func (*Config) Delete

func (c *Config) Delete(name string) error

Delete removes a configuration entry

func (*Config) GetCurrent

func (c *Config) GetCurrent() *ConfigEntry

GetCurrent returns the current active configuration entry. If the current configuration doesn't exist, it falls back to the "default" configuration, or creates a default entry if no configurations exist.

Example:

current := config.GetCurrent()
fmt.Printf("Current endpoint: %s\n", current.Endpoint)

func (*Config) Save

func (c *Config) Save(configDir string) error

Save writes the configuration to the specified config directory. Creates the directory if it doesn't exist and writes the configuration as JSON.

Example:

err := config.Save("/path/to/config")
if err != nil {
    log.Fatal(err)
}

func (*Config) SetCurrent

func (c *Config) SetCurrent(name string) error

SetCurrent sets the current active configuration

func (*Config) SetValue

func (c *Config) SetValue(name, key, value string) error

SetValue sets a value in a configuration entry

func (*Config) Validate

func (c *Config) Validate() []string

Validate checks if the configuration is valid

type ConfigEntry

type ConfigEntry struct {
	Endpoint string            `json:"endpoint"` // GraphQL endpoint URL
	Headers  map[string]string `json:"headers"`  // HTTP headers to send with requests
	Defaults struct {
		Out string `json:"out"` // default output format (json, pretty, raw)
	} `json:"defaults"`
	Comment string `json:"_comment,omitempty"` // AI-friendly documentation
}

ConfigEntry represents a single configuration for a GraphQL endpoint. It contains the endpoint URL, headers, default output format, and optional documentation.

type EnumValue

type EnumValue struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

EnumValue represents an enum value

type ErrorInfo

type ErrorInfo struct {
	Code    string                 `json:"code"`
	Message string                 `json:"message"`
	Details string                 `json:"details,omitempty"`
	Type    string                 `json:"type,omitempty"`
	Context map[string]interface{} `json:"context,omitempty"`
}

ErrorInfo provides structured error information

type FieldDescription

type FieldDescription struct {
	RootType    string         `json:"rootType"`
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	Type        string         `json:"type"`
	Arguments   []FieldSummary `json:"arguments,omitempty"`
}

FieldDescription represents a field description

type FieldSummary

type FieldSummary struct {
	Name         string         `json:"name"`
	Description  string         `json:"description,omitempty"`
	Type         string         `json:"type"`
	Signature    string         `json:"signature"`
	DefaultValue string         `json:"defaultValue,omitempty"`
	Arguments    []FieldSummary `json:"arguments,omitempty"`
}

FieldSummary represents a field summary

type Formatter

type Formatter interface {
	FormatStructured(data interface{}, quiet bool) error
	FormatStructuredError(err error, code string, quiet bool) error
	FormatStructuredErrorWithContext(err error, code string, errorType string, context map[string]interface{}, quiet bool) error
	FormatResponse(response *Response, mode string) error
	SetOutput(writer io.Writer)
	SetErrorOutput(writer io.Writer)
}

Formatter defines the interface for output formatting. Implementations can format data as JSON, table, YAML, or other formats.

func NewFormatter

func NewFormatter(format string) Formatter

NewFormatter creates a new formatter using the default registry Returns the default JSON formatter if the requested format is not found

type FormatterFactory

type FormatterFactory func() Formatter

FormatterFactory creates a new formatter instance. This function type is used to register formatters in the registry.

type FormatterRegistry

type FormatterRegistry struct {
	// contains filtered or unexported fields
}

FormatterRegistry manages available formatters and provides a way to register and retrieve formatters by name.

func NewFormatterRegistry

func NewFormatterRegistry() *FormatterRegistry

NewFormatterRegistry creates a new formatter registry with default formatters (JSON, Table, YAML) already registered.

Example:

registry := gqlt.NewFormatterRegistry()
formatter, err := registry.Get("json")

func (*FormatterRegistry) Get

func (r *FormatterRegistry) Get(format string) (Formatter, error)

Get creates a new formatter instance for the specified format

func (*FormatterRegistry) List

func (r *FormatterRegistry) List() []string

List returns all registered formatter names

func (*FormatterRegistry) Register

func (r *FormatterRegistry) Register(name string, factory FormatterFactory)

Register adds a new formatter to the registry

type Input

type Input struct{}

Input handles input operations for loading queries, variables, headers, and files. It provides utilities for parsing and loading various types of input data.

func NewInput

func NewInput() *Input

NewInput creates a new input handler instance.

Example:

input := gqlt.NewInput()
query, err := input.LoadQuery("", "query.graphql")

func (*Input) LoadHeaders

func (i *Input) LoadHeaders(headers []string) map[string]string

LoadHeaders parses header strings into a map. Each header string should be in the format "Key: Value".

Example:

headers := input.LoadHeaders([]string{
    "Authorization: Bearer token",
    "Content-Type: application/json",
})

func (*Input) LoadQuery

func (i *Input) LoadQuery(query, queryFile string) (string, error)

LoadQuery loads a GraphQL query from a string or file. If query is provided, it returns the query string directly. If queryFile is provided, it reads and returns the file contents. If both are provided, query takes precedence.

Example:

query, err := input.LoadQuery("", "query.graphql")
if err != nil {
    log.Fatal(err)
}

func (*Input) LoadVariables

func (i *Input) LoadVariables(vars, varsFile string) (map[string]interface{}, error)

LoadVariables loads GraphQL variables from a JSON string or file. If vars is provided, it parses the JSON string directly. If varsFile is provided, it reads and parses the file contents. If both are provided, vars takes precedence.

Example:

variables, err := input.LoadVariables(`{"id": "123"}`, "")
if err != nil {
    log.Fatal(err)
}

func (*Input) ParseFiles

func (i *Input) ParseFiles(files []string) (map[string]string, error)

ParseFiles parses file upload specifications

func (*Input) ParseFilesFromList

func (i *Input) ParseFilesFromList(filesListPath string) ([]string, error)

ParseFilesFromList parses file upload specifications from a file

type Introspect

type Introspect struct {
	// contains filtered or unexported fields
}

Introspect handles GraphQL schema introspection operations. It provides utilities for introspecting GraphQL schemas and saving them to files.

func NewIntrospect

func NewIntrospect(client *Client) *Introspect

NewIntrospect creates a new introspection handler for the specified client.

Example:

client := gqlt.NewClient("https://api.example.com/graphql", nil)
introspect := gqlt.NewIntrospect(client)

func (*Introspect) IntrospectSchema

func (i *Introspect) IntrospectSchema() (*Response, error)

IntrospectSchema performs GraphQL introspection to get the schema from the endpoint. Returns a Response containing the complete GraphQL schema information.

Example:

schema, err := introspect.IntrospectSchema()
if err != nil {
    log.Fatal(err)
}

func (*Introspect) SaveSchema

func (i *Introspect) SaveSchema(schema *Response, filePath string) error

SaveSchema saves a schema response to a JSON file. The file will contain the complete introspection response in formatted JSON.

Example:

err := introspect.SaveSchema(schema, "schema.json")
if err != nil {
    log.Fatal(err)
}

type JSONFormatter

type JSONFormatter struct {
	// contains filtered or unexported fields
}

JSONFormatter implements Formatter for JSON output

func (*JSONFormatter) FormatJSON

func (f *JSONFormatter) FormatJSON(data interface{}) error

FormatJSON formats data as JSON with indentation

func (*JSONFormatter) FormatPretty

func (f *JSONFormatter) FormatPretty(data interface{}) error

FormatPretty formats data as colorized JSON

func (*JSONFormatter) FormatResponse

func (f *JSONFormatter) FormatResponse(response *Response, mode string) error

FormatResponse formats a GraphQL response

func (*JSONFormatter) FormatStructured

func (f *JSONFormatter) FormatStructured(data interface{}, quiet bool) error

FormatStructured formats data as structured JSON output

func (*JSONFormatter) FormatStructuredError

func (f *JSONFormatter) FormatStructuredError(err error, code string, quiet bool) error

FormatStructuredError formats an error as structured output

func (*JSONFormatter) FormatStructuredErrorWithContext

func (f *JSONFormatter) FormatStructuredErrorWithContext(err error, code string, errorType string, context map[string]interface{}, quiet bool) error

FormatStructuredErrorWithContext formats an error with additional context

func (*JSONFormatter) SetErrorOutput

func (f *JSONFormatter) SetErrorOutput(writer io.Writer)

SetErrorOutput sets the error output writer for the formatter

func (*JSONFormatter) SetOutput

func (f *JSONFormatter) SetOutput(writer io.Writer)

SetOutput sets the output writer for the formatter

func (*JSONFormatter) WriteToFile

func (f *JSONFormatter) WriteToFile(data interface{}, filename string) error

WriteToFile writes data to a file

type MetaInfo

type MetaInfo struct {
	Command   string                 `json:"command,omitempty"`
	Timestamp string                 `json:"timestamp,omitempty"`
	Duration  string                 `json:"duration,omitempty"`
	Config    string                 `json:"config,omitempty"`
	Endpoint  string                 `json:"endpoint,omitempty"`
	Operation string                 `json:"operation,omitempty"`
	Variables map[string]interface{} `json:"variables,omitempty"`
}

MetaInfo provides metadata about the operation

type Response

type Response struct {
	Data       interface{}            `json:"data"`
	Errors     []interface{}          `json:"errors,omitempty"`
	Extensions map[string]interface{} `json:"extensions,omitempty"`
}

Response represents a GraphQL response containing data, errors, and extensions. The Data field contains the actual response data, Errors contains any GraphQL errors, and Extensions contains additional metadata from the server.

type Schema

type Schema struct {
	Endpoint    string `json:"endpoint"`
	Headers     string `json:"headers"`
	DefaultsOut string `json:"defaults.out"`
}

Schema represents the configuration schema for AI understanding

func GetSchema

func GetSchema() *Schema

GetSchema returns the configuration schema for AI understanding

type StructuredOutput

type StructuredOutput struct {
	Success bool        `json:"success"`
	Data    interface{} `json:"data,omitempty"`
	Error   *ErrorInfo  `json:"error,omitempty"`
	Meta    *MetaInfo   `json:"meta,omitempty"`
}

StructuredOutput represents a structured response for AI agents

type Summary

type Summary struct {
	TotalTypes       int    `json:"totalTypes"`
	QueryType        string `json:"queryType,omitempty"`
	MutationType     string `json:"mutationType,omitempty"`
	SubscriptionType string `json:"subscriptionType,omitempty"`
}

Summary represents a schema summary

type TableFormatter

type TableFormatter struct {
	// contains filtered or unexported fields
}

TableFormatter implements Formatter for table output

func (*TableFormatter) FormatResponse

func (f *TableFormatter) FormatResponse(response *Response, mode string) error

FormatResponse formats a GraphQL response

func (*TableFormatter) FormatStructured

func (f *TableFormatter) FormatStructured(data interface{}, quiet bool) error

FormatStructured formats data as structured table output

func (*TableFormatter) FormatStructuredError

func (f *TableFormatter) FormatStructuredError(err error, code string, quiet bool) error

FormatStructuredError formats an error as structured table output

func (*TableFormatter) FormatStructuredErrorWithContext

func (f *TableFormatter) FormatStructuredErrorWithContext(err error, code string, errorType string, context map[string]interface{}, quiet bool) error

FormatStructuredErrorWithContext formats an error with additional context

func (*TableFormatter) SetErrorOutput

func (f *TableFormatter) SetErrorOutput(writer io.Writer)

SetErrorOutput sets the error output writer for the formatter

func (*TableFormatter) SetOutput

func (f *TableFormatter) SetOutput(writer io.Writer)

SetOutput sets the output writer for the formatter

type TypeDescription

type TypeDescription struct {
	Name        string         `json:"name"`
	Kind        string         `json:"kind"`
	Description string         `json:"description,omitempty"`
	Fields      []FieldSummary `json:"fields,omitempty"`
	InputFields []FieldSummary `json:"inputFields,omitempty"`
	EnumValues  []EnumValue    `json:"enumValues,omitempty"`
}

TypeDescription represents a type description

type YAMLFormatter

type YAMLFormatter struct {
	// contains filtered or unexported fields
}

YAMLFormatter implements Formatter for YAML output

func (*YAMLFormatter) FormatResponse

func (f *YAMLFormatter) FormatResponse(response *Response, mode string) error

FormatResponse formats a GraphQL response

func (*YAMLFormatter) FormatStructured

func (f *YAMLFormatter) FormatStructured(data interface{}, quiet bool) error

FormatStructured formats data as structured YAML output

func (*YAMLFormatter) FormatStructuredError

func (f *YAMLFormatter) FormatStructuredError(err error, code string, quiet bool) error

FormatStructuredError formats an error as structured YAML output

func (*YAMLFormatter) FormatStructuredErrorWithContext

func (f *YAMLFormatter) FormatStructuredErrorWithContext(err error, code string, errorType string, context map[string]interface{}, quiet bool) error

FormatStructuredErrorWithContext formats an error with additional context

func (*YAMLFormatter) SetErrorOutput

func (f *YAMLFormatter) SetErrorOutput(writer io.Writer)

SetErrorOutput sets the error output writer for the formatter

func (*YAMLFormatter) SetOutput

func (f *YAMLFormatter) SetOutput(writer io.Writer)

SetOutput sets the output writer for the formatter

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL