### Kafka Integration Example Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md An example demonstrating the setup of a Kafka producer and a mutation to publish user events. It shows how to configure the producer with compression and batching, and how the @kafkaPublish directive uses arguments for the message key. ```graphql extend schema @link( url: "https://grafbase.com/extensions/kafka/0.1.1" import: ["@kafkaProducer", "@kafkaPublish", "@kafkaSubscription"] ) @kafkaProducer( name: "userEventProducer" provider: "default" topic: "user-events" config: { compression: GZIP partitions: [0, 1, 2] batch: { lingerMs: 5, maxSizeBytes: 8192 } } ) type Mutation { publishUserEvent(id: String!, input: UserEventInput!): Boolean! @kafkaPublish(producer: "userEventProducer", key: "user-{{args.id}}") } input UserEventInput { email: String! name: String! eventType: String! } ``` -------------------------------- ### Install Grafbase Extension Command Source: https://github.com/grafbase/extensions/blob/main/extensions/authenticated/README.md The command-line interface command to execute for installing Grafbase extensions. This should be run before starting the Grafbase gateway. ```bash grafbase extension install ``` -------------------------------- ### Install Grafbase PostgreSQL CLI Source: https://github.com/grafbase/extensions/blob/main/cli/postgres/README.md Installs the latest version of the Grafbase PostgreSQL CLI using a quick install script. This script automatically detects your system and installs the binary to `~/.grafbase/bin`. ```bash curl -fsSL https://raw.githubusercontent.com/grafbase/extensions/refs/heads/main/cli/postgres/install.sh | bash ``` -------------------------------- ### Install Kafka Extension Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md Instructions for installing the Kafka extension using Grafbase Gateway configuration. This involves adding the extension to the configuration file and running the installation command. ```toml [extensions.kafka] version = "0.2" ``` -------------------------------- ### Run Grafbase Extension Install Command Source: https://github.com/grafbase/extensions/blob/main/extensions/oauth-protected-resource/README.md Execute this command in your terminal after configuring the extension to complete the installation process. ```bash grafbase extension install ``` -------------------------------- ### Install Grafbase REST Extension Source: https://github.com/grafbase/extensions/blob/main/extensions/rest/README.md Configuration snippet for installing the Grafbase REST extension in `grafbase.toml`. Specifies the extension name and version for automatic installation. ```toml [extensions.rest] version = "0.5" ``` -------------------------------- ### Install Grafbase PostgreSQL CLI from Source Source: https://github.com/grafbase/extensions/blob/main/cli/postgres/README.md Builds and installs the Grafbase PostgreSQL CLI from source using Cargo. This method requires a Rust development environment. ```cargo cargo install --path . ``` -------------------------------- ### Install JWT Extension Source: https://github.com/grafbase/extensions/blob/main/extensions/jwt/README.md Steps to install the JWT extension for the Grafbase Gateway. This involves adding the extension to the Grafbase configuration file and running the installation command. ```toml # grafbase.toml [extensions.jwt] version = "1" ``` ```bash grafbase extension install ``` -------------------------------- ### Install Grafbase Authenticated Extension Configuration Source: https://github.com/grafbase/extensions/blob/main/extensions/authenticated/README.md Configuration snippet for the grafbase.toml file to enable the authenticated extension. This specifies the extension name and version required for installation. ```toml # grafbase.toml [extension.authenticated] version = "1.0" ``` -------------------------------- ### Kafka Consumer Start Offset Configuration Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md Specifies how to configure the starting offset for Kafka consumers, either by a preset value (LATEST/EARLIEST) or a specific offset number. ```graphql input KafkaConsumerStartOffset @oneOf { preset: KafkaConsumerStartOffsetPreset offset: Int } enum KafkaConsumerStartOffsetPreset { LATEST EARLIEST } ``` -------------------------------- ### Install Grafbase Extensions (Bash) Source: https://github.com/grafbase/extensions/blob/main/extensions/requires-scopes/README.md This bash command is executed in the terminal to install Grafbase extensions that have been configured in `grafbase.toml`. It should be run before starting the Grafbase gateway. ```bash grafbase extension install ``` -------------------------------- ### Multiple Kafka Provider Configuration (TOML) Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md Configuration example for setting up multiple Kafka clusters with different endpoints, TLS, and authentication methods using TOML. ```toml [[extensions.kafka.config.endpoint]] name = "production" bootstrap_servers = ["prod-kafka-1:9092", "prod-kafka-2:9092"] [extensions.kafka.config.endpoint.tls] system_ca = true [extensions.kafka.config.endpoint.authentication] sasl_scram = { username = "prod_user", password = "prod_password", mechanism = "sha512" } [[extensions.kafka.config.endpoint]] name = "analytics" bootstrap_servers = ["analytics-kafka:9092"] [extensions.kafka.config.endpoint.authentication] sasl_plain = { username = "analytics_user", password = "analytics_password" } ``` -------------------------------- ### NATS Publish Example Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md Example of using the `@natsPublish` directive in a GraphQL mutation. It demonstrates publishing user event data to a NATS subject dynamically constructed with an argument. ```graphql type Mutation { publishUserEvent(id: Int!, input: UserEventInput!): Boolean! @natsPublish(subject: "publish.user.{{args.id}}.events") } input UserEventInput { email: String! name: String! } ``` -------------------------------- ### Basic Kafka Subscription Example Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md Demonstrates a basic GraphQL subscription to a Kafka topic, filtering messages by a user ID in the message key. ```graphql type Subscription { userEvents(userId: String!): UserEvent! @kafkaSubscription(topic: "user-events", keyFilter: "user-{{args.userId}}") } type UserEvent { email: String! name: String! eventType: String! timestamp: String! } ``` -------------------------------- ### NATS Request/Reply Example: Get User Details Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md Demonstrates using the `@natsRequest` directive to fetch user details by ID. A request is sent to a templated subject (`user.details.`) with a specified timeout, and the response is mapped to the `UserDetails` type. ```graphql type Query { getUserDetails(id: String!): UserDetails! @natsRequest(subject: "user.details.{{args.id}}", timeoutMs: 2000) } type UserDetails { id: String! name: String! email: String! createdAt: String! role: String! } ``` -------------------------------- ### NATS Publish Example Mutation Call Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md Example GraphQL mutation query to trigger the `publishUserEvent` mutation, sending user data to the NATS topic defined by the `@natsPublish` directive. ```graphql mutation PublishUserEvent($id: Int!, $email: String!, $name: String!) { publishUserEvent(id: $id, input: { email: $email, name: $name }) } ``` -------------------------------- ### NATS Publish Example Payload Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md The resulting JSON payload that would be published to the NATS subject `publish.user.1.events` when the example mutation is called with specific arguments. ```json { "email": "john@example.com", "name": "John Doe" } ``` -------------------------------- ### Kafka Consumer Configuration Input Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md Defines the input structure for configuring Kafka consumers, including batching, wait times, start offsets, and specific partitions. ```graphql input KafkaConsumerConfiguration { minBatchSize: Int maxBatchSize: Int maxWaitTimeMs: Int startOffset: KafkaConsumerStartOffset! = { preset: LATEST } partitions: [Int!] } ``` -------------------------------- ### Basic NATS Subscription Example Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md Example of a basic NATS subscription using the `@natsSubscription` directive. It subscribes to a dynamic subject based on a GraphQL argument, allowing clients to receive specific user events. ```graphql type Subscription { userEvents(userId: Int!): UserEvent! @natsSubscription(subject: "user.{{args.userId}}.events") } type UserEvent { type: String! userId: Int! timestamp: String! data: JSON } ``` -------------------------------- ### Install OAuth Protected Resource Extension Source: https://github.com/grafbase/extensions/blob/main/extensions/oauth-protected-resource/README.md Configuration snippet for installing the OAuth 2.0 Protected Resource Metadata extension in your Grafbase project's configuration file. ```toml # grafbase.toml [extensions.oauth-protected-resource] version = "0.1" ``` -------------------------------- ### Build NATS Extension from Source Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md Command to manually build the NATS extension from its source code. This is an alternative to installing from a registry. ```bash grafbase extension build ``` -------------------------------- ### Connect to PostgreSQL with mTLS using psql Source: https://github.com/grafbase/extensions/blob/main/docker/postgres-mtls/README.md Provides the necessary `psql` command to connect to a PostgreSQL database configured with mutual TLS (mTLS). This command includes parameters for host, port, database name, user, SSL mode, and paths to the CA certificate, client certificate, and client key. Ensure you execute this command from the extensions root directory. ```bash psql "host=localhost \ port=5433 \ dbname=postgres \ user=testuser \ sslmode=verify-full \ sslrootcert=./docker/postgres-mtls/certs/ca.crt \ sslcert=./docker/postgres-mtls/certs/client.crt \ sslkey=./docker/postgres-mtls/certs/client.key" ``` ```bash psql postgresql://testuser@localhost:5433/postgres?sslmode=verify-full&sslrootcert=./docker/postgres-mtls/certs/ca.crt&sslcert=./docker/postgres-mtls/certs/client.crt&sslkey=./docker/postgres-mtls/certs/client.key ``` -------------------------------- ### JetStream NATS Subscription Example Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md Example demonstrating a JetStream subscription with the `@natsSubscription` directive. It configures a durable consumer to subscribe to a wildcard subject, retrieving the last message for specific scenarios. ```graphql type Subscription { orderUpdates: OrderUpdate! @natsSubscription( subject: "orders.>" streamConfig: { streamName: "ORDERS" consumerName: "order-processor" durableName: "order-updates" deliverPolicy: { type: LAST } } ) } type OrderUpdate { orderId: String! status: String! updatedAt: String! } ``` -------------------------------- ### Example REST API Response Structure Source: https://github.com/grafbase/extensions/blob/main/extensions/rest/README.md Illustrates the typical JSON structure returned by the `https://restcountries.com/v3.1/all` API endpoint, showing nested data that needs selection. ```json [ { "name": { "common": "South Georgia", "official": "South Georgia and the South Sandwich Islands", "nativeName": { "eng": { "official": "South Georgia and the South Sandwich Islands", "common": "South Georgia" } } }, ... } ] ``` -------------------------------- ### PostgreSQL Schema Example Source: https://github.com/grafbase/extensions/blob/main/extensions/postgres/README.md Illustrates a sample PostgreSQL database schema with tables for users and profiles, including primary keys, foreign key constraints, and JSONB data types. ```sql CREATE TABLE "users" ( id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, username VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, metadata JSONB DEFAULT '{}' ); CREATE TABLE profiles ( id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, user_id BIGINT NOT NULL REFERENCES "users"(id) ON DELETE CASCADE, first_name VARCHAR(100), last_name VARCHAR(100) ); ``` -------------------------------- ### Table Filtering Configuration Source: https://github.com/grafbase/extensions/blob/main/cli/postgres/README.md Example TOML configuration demonstrating how to use `table_allowlist` and `table_denylist` to control which tables are included or excluded for specific schemas in Grafbase. ```toml # Example of table filtering in config.toml extension_url = "https://grafbase.com/extensions/postgres/0.4.9" [schemas.public] table_allowlist = ["users", "posts"] [schemas.internal] table_denylist = ["audit_logs", "system_metrics"] ``` -------------------------------- ### Install Requires Scopes Extension (TOML) Source: https://github.com/grafbase/extensions/blob/main/extensions/requires-scopes/README.md This TOML configuration block is used within `grafbase.toml` to install the Requires Scopes extension. It specifies the extension name and its version, enabling its functionality for the Grafbase project. ```toml # grafbase.toml [extension.requires-scopes] version = "1.0" ``` -------------------------------- ### Grafbase gRPC Extension Schema Definition Source: https://github.com/grafbase/extensions/blob/main/extensions/grpc/README.md An example of how to extend the Grafbase schema to include the gRPC extension and define protobuf messages and services. This involves linking the extension and using @protoMessages and @protoServices directives. ```graphql extend schema @link(url: "https://grafbase.com/extensions/grpc/0.2.0", import: ["@grpcMethod", "@protoMessages", "@protoServices"]) @protoMessages(definitions: [ { name: "Point" fields: [ { name: "latitude", type: "int32", number: 1 } { name: "longitude", type: "int32", number: 2 } ] }, { name: "Feature" fields: [ { name: "name", type: "string", number: 1 } { name: "location", type: "Point", number: 2 } ] } ]) @protoServices(definitions: [ { name: "routeguide.RouteGuide" methods: [ { name: "GetFeature", inputType: "Point", outputType: "Feature" } ] }} ]) ``` -------------------------------- ### Schema and Table Filtering Configuration Source: https://github.com/grafbase/extensions/blob/main/cli/postgres/README.md Example TOML configuration for Grafbase extensions, demonstrating how to control schema introspection using `schema_allowlist` and `schema_denylist`. This allows selective inclusion or exclusion of database schemas. ```toml extension_url = "https://grafbase.com/extensions/postgres/0.4.7" schema_allowlist = ["public", "app"] schema_denylist = ["internal"] ``` -------------------------------- ### NATS Request/Reply Example: Authenticate User Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md Shows how to use `@natsRequest` for an authentication service. It sends authentication credentials in the request body to the `auth.service` subject and expects an `AuthResponse` containing a token and user information, with a configured timeout. ```graphql type Query { authenticateUser(input: AuthInput!): AuthResponse! @natsRequest(subject: "auth.service", timeoutMs: 3000) } input AuthInput { username: String! password: String! } type AuthResponse { token: String userId: String success: Boolean! message: String } ``` -------------------------------- ### Kafka Extension Build Artifacts Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md Lists the output files generated after building the Kafka extension from source. These artifacts include the WebAssembly component and its manifest. ```bash build/ ├── extension.wasm └── manifest.json ``` -------------------------------- ### Get User Preferences (GET with Selection) Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md Retrieves only the preferences field from a user profile using jq-style selection. ```graphql type Query { getUserPreferences(userId: String!): JSON @natsKeyValue( bucket: "user-profiles" key: "{{args.userId}}" action: GET selection: ".preferences" ) } ``` -------------------------------- ### Build Kafka Extension From Source Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md Steps to manually build the Kafka extension from its source code. This process generates Wasm components and manifest files required for loading the extension. ```bash grafbase extension build ``` -------------------------------- ### Get User Profile (GET) Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md Retrieves a user profile from the "user-profiles" bucket using the userId as the key. ```graphql type Query { getUserProfile(userId: String!): UserProfile @natsKeyValue(bucket: "user-profiles", key: "{{args.userId}}", action: GET) } type UserProfile { name: String! email: String! preferences: JSON lastUpdated: String! } ``` -------------------------------- ### Grafbase PostgreSQL CLI Usage Source: https://github.com/grafbase/extensions/blob/main/cli/postgres/README.md Documentation for the `grafbase-postgres` CLI tool, covering its core functionality, options, and usage patterns for introspecting PostgreSQL databases. ```APIDOC grafbase-postgres [GLOBAL OPTIONS] GLOBAL OPTIONS: -d, --database-url Connection string to the PostgreSQL database. Must precede the subcommand. SUBCOMMANDS: introspect Introspects the PostgreSQL database schema. Introspect Command Options: -c, --config Specify configuration file for introspection. Defaults to `./grafbase-postgres.toml`. Usage Examples: Output SDL to Terminal: grafbase-postgres \ --database-url "postgres://user:pass@localhost:5432/mydb" \ introspect \ --config grafbase-postgres.toml Save SDL to a File: grafbase-postgres \ --database-url "postgres://user:pass@localhost:5432/mydb" \ introspect \ --config grafbase-postgres.toml > schema.graphql Environment Variables: DATABASE_URL: Connection string to your PostgreSQL database. If a .env file exists in the current directory, it will be used. TLS Connection Parameters (in DATABASE_URL): sslmode=verify-full sslrootcert=/path/to/ca.crt sslcert=/path/to/client.crt sslkey=/path/to/client.key ``` -------------------------------- ### Load Grafbase Extension from Build Directory Source: https://github.com/grafbase/extensions/blob/main/extensions/rest/README.md Configuration snippet for loading a manually built Grafbase REST extension from a specified file path in `grafbase.toml`. This is used when building from source. ```toml [extensions.rest] path = "/path/to/build" ``` -------------------------------- ### Configure Kafka Extension Path Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md Specifies how to configure the Grafbase Gateway to load the Kafka extension from a custom build path. This is used when building from source. ```toml [extensions.kafka] path = "/path/to/build" ``` -------------------------------- ### Build and Configure Grafbase Postgres Extension Locally Source: https://github.com/grafbase/extensions/blob/main/extensions/postgres/README.md Instructions for building the Grafbase Postgres extension locally and configuring the Grafbase Gateway to use the generated Wasm module and manifest. This involves running a build command and updating the `path` in `grafbase.toml`. ```bash grafbase extension build ``` ```toml # grafbase.toml [extensions.postgres] path = "/path/to/your/build" # Update this path ``` -------------------------------- ### Run Grafbase Postgres Extension Tests Source: https://github.com/grafbase/extensions/blob/main/extensions/postgres/README.md Commands to set up the test environment using Docker Compose and execute the extension's test suite with Cargo. It also includes an optimization for faster test execution by pre-compiling the extension. ```bash docker compose up -d cargo test ``` ```bash grafbase extension build PREBUILT_EXTENSION=1 cargo nextest run ``` -------------------------------- ### Grafbase Gateway NATS Extension Installation Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md Configuration snippet to add the NATS extension to your Grafbase Gateway configuration file. This specifies the extension version. ```toml [extensions.nats] version = "0.5" ``` -------------------------------- ### Build Grafbase Extension from Source Source: https://github.com/grafbase/extensions/blob/main/extensions/rest/README.md Command to build the Grafbase REST extension from its source code. This process generates the necessary WebAssembly component and manifest files. ```bash grafbase extension build ``` -------------------------------- ### Advanced Kafka Consumer Subscription Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md Shows a GraphQL subscription with advanced Kafka consumer configuration, including earliest offset, batch size, wait time, and specific partitions. ```graphql type Subscription { orderUpdates: OrderUpdate! @kafkaSubscription( topic: "order-updates" consumerConfig: { startOffset: { preset: EARLIEST } maxBatchSize: 100 maxWaitTimeMs: 5000 partitions: [0, 1, 2] } ) } type OrderUpdate { orderId: String! status: String! updatedAt: String! customerId: String! } ``` -------------------------------- ### Published Kafka Message Payload Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md The JSON payload of a Kafka message published by the example mutation. This shows the structure of the data sent to the Kafka topic, derived from the mutation input. ```json { "email": "john@example.com", "name": "John Doe", "eventType": "profile_update" } ``` -------------------------------- ### Configure Kafka Endpoint Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md Defines the basic configuration for a Kafka endpoint, including the name and bootstrap servers. Multiple endpoints can be configured. ```toml [[extensions.kafka.config.endpoint]] name = "default" bootstrap_servers = ["localhost:9092"] ``` -------------------------------- ### Grafbase PostgreSQL CLI Configuration Source: https://github.com/grafbase/extensions/blob/main/cli/postgres/README.md Defines the structure and options for the `grafbase-postgres.toml` configuration file used to customize the introspection process. ```toml # The URL of the extension, which appears at the top of the GraphQL SDL. extension_url = "https://grafbase.com/extensions/postgres/0.3.0" # The default schema, which we'll omit from the SDL output. # Defaults to "public" if you don't specify it default_schema = "public" # The name of the database the virtual subgraph should use. This # maps to a Postgres database name in your gateway configuration. # Defaults to "default" if you don't specify it database_name = "default" # Enable mutations (write operations) globally for the whole database. # Defaults to true if you omit this setting. enable_mutations = true # Enable queries (read operations) globally for the whole database. # Defaults to true if you omit this setting. enable_queries = true # Schema allowlist: An array of schema names to include in the introspection. # If provided, only schemas in this list will be included. # If not defined or null, all schemas will be included (unless in the denylist). # If empty, no schemas will be included. schema_allowlist = null # Schema denylist: An array of schema names to exclude from the introspection. # Schemas in this list will be excluded even if they appear in the allowlist. # This takes precedence over the schema_allowlist. schema_denylist = [] # Configure schemas for this database. Key-value from schema name to configuration. schemas = {} [schemas.public] # Enable mutations (write operations) globally for the whole schema. # Takes precedence over the global setting. Defaults to true if you omit this setting. enable_mutations = true # Enable queries (read operations) globally for the whole database. # Takes precedence over the global setting. Defaults to true if you omit this setting. enable_queries = true ``` -------------------------------- ### GraphQL Schema with @authenticated Directive Source: https://github.com/grafbase/extensions/blob/main/extensions/authenticated/README.md Example GraphQL schema demonstrating the usage of the @authenticated directive. It shows how to link the extension and apply the directive to protect specific fields, making them accessible only to authenticated users. ```graphql # subgraph schema extend schema @link( url: "https://grafbase.com/extensions/authenticated/1.0.0" import: ["@authenticated"] ) type Query { public: String! mustBeAuthenticated: String! @authenticated } ``` -------------------------------- ### GraphQL Schema with @requiresScopes Directive Source: https://github.com/grafbase/extensions/blob/main/extensions/requires-scopes/README.md Example of extending a GraphQL schema to utilize the `@requiresScopes` directive. This directive is applied to fields to control access based on provided OAuth scopes, demonstrating single scope, AND logic, and OR logic. ```graphql extend schema @link(url: "https://grafbase.com/extensions/requires-scopes/1.0.5", import: ["@requiresScopes"]) type Query { public: String! hasReadScope: String @requiresScopes(scopes: "read") hasReadAndWriteScope: String @requiresScopes(scopes: [["read", "write"]]) hasReadOrWriteScope: String @requiresScopes(scopes: [["read"], ["write"]]) } ``` -------------------------------- ### Configure View Settings in TOML Source: https://github.com/grafbase/extensions/blob/main/cli/postgres/README.md Configures settings for PostgreSQL views, which require explicit definition of unique keys and column properties due to schema information limitations. Enables queries for views and defines their structure. ```toml [schemas.public.views.restricted_users] enable_queries = true unique_keys = [] columns = {} relations = {} derives = {} ``` -------------------------------- ### Construct Dynamic Path with Arguments Source: https://github.com/grafbase/extensions/blob/main/extensions/rest/README.md Explains how to dynamically construct the path for a REST endpoint request using template variables that reference input arguments. This allows for flexible API calls based on query or mutation parameters. ```graphql type Mutation { getCountry(id: Int!): Country @rest( endpoint: "countries" http: { GET: "/fetch/{{ args.id }}" } selection: "{ name: .name.official }" ) } ``` -------------------------------- ### NATS Key-Value Store Directive Definition Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md Defines the `@natsKeyValue` directive for interacting with NATS JetStream key-value stores. It supports operations like CREATE, PUT, GET, and DELETE on specified buckets and keys, with options for body, selection, and provider. ```APIDOC directive @natsKeyValue( provider: String! = "default" bucket: UrlTemplate! key: UrlTemplate! action: NatsKeyValueAction! body: Body = { selection: ".args.input" } selection: UrlTemplate ) on FIELD_DEFINITION enum NatsKeyValueAction { CREATE PUT GET DELETE } # UrlTemplate: A string that supports templating using GraphQL arguments, e.g., {{args.myArgument}} # Body: Defines the message body, supporting selection from arguments, e.g., { selection: ".args.input" } (used for PUT/CREATE) # selection: JQ-style selection to apply to the response payload (used for GET) # Parameters: # - provider: The NATS provider to use. Default is 'default'. # - bucket: The bucket name to operate on. Supports templating. # - key: The key name to operate on. Supports templating. # - action: The key-value operation to perform (CREATE, PUT, GET, DELETE). # - body: The message body for PUT/CREATE actions. # - selection: JQ-style selection for GET action response. # Return Value: The field typically returns a boolean indicating success for most actions, or the value for GET. ``` -------------------------------- ### OAuth Protected Resource Metadata Configuration Source: https://github.com/grafbase/extensions/blob/main/extensions/jwt/README.md Defines the configuration parameters for serving OAuth Protected Resource Metadata via the Grafbase JWT extension. This setup allows the JWT extension to automatically provide metadata for protected resources, eliminating the need for a separate extension when JWT authentication is already in use. ```config # Required - The resource identifier URL for this protected resource resource = "https://api.example.com" # Optional - List of authorization servers that can issue tokens for this resource authorization_servers = ["https://auth.example.com", "https://auth-backup.example.com"] # Optional - List of supported scopes scopes_supported = ["read", "write", "admin"] # Optional - Supported methods for presenting bearer tokens bearer_methods_supported = ["header", "body"] # Optional - JWKS URI for the resource server's signing keys (defaults to jwt.config.url) jwks_uri = "https://api.example.com/.well-known/jwks.json" # Optional - Human-readable information resource_name = "Example API" resource_documentation = "https://docs.example.com/api" resource_policy_uri = "https://example.com/api/policy" resource_tos_uri = "https://example.com/api/terms" # Optional - Security features tls_client_certificate_bound_access_tokens = true # When at least the resource is defined, the JWT extension will serve the OAuth Protected Resource Metadata at the configured path (defaulting to `/.well-known/oauth-protected-resource`). This eliminates the need to install the separate `oauth-protected-resource` extension if you're already using JWT authentication. ``` -------------------------------- ### Kafka Producer Configuration Directive Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md Defines a Kafka producer at the schema level, specifying its name, topic, and provider. Includes optional configuration for compression, partitions, and batching. ```APIDOC directive @kafkaProducer( name: String! topic: String! provider: String = "default" config: KafkaProducerConfiguration ) on SCHEMA input KafkaProducerConfiguration { compression: KafkaCompression partitions: [Int] batch: KafkaBatchConfiguration } enum KafkaCompression { GZIP SNAPPY LZ4 ZSTD } input KafkaBatchConfiguration { lingerMs: Int maxSizeBytes: Int } # Parameters: # - name: The unique name of the Kafka producer, used for referencing. # - topic: The Kafka topic to publish messages to. # - provider: The name of the Kafka provider in Grafbase configuration (defaults to 'default'). # - config: Optional configuration options for the producer. # - compression: Algorithm for message compression (GZIP, SNAPPY, LZ4, ZSTD). # - partitions: List of partition IDs for publishing. # - batch: # - lingerMs: Time in milliseconds before sending a batch. # - maxSizeBytes: Maximum size in bytes for a batch. ``` -------------------------------- ### Create User Profile (CREATE) Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md Stores a user profile in the "user-profiles" bucket using userId as the key. If the value exists, the mutation returns an error. Profile data comes from the input argument. The return value is the sequence number of the operation. ```graphql type Mutation { saveUserProfile(userId: String!, profile: UserProfileInput!): String! @natsKeyValue( bucket: "user-profiles" key: "{{args.userId}}" action: CREATE ) } input UserProfileInput { name: String! email: String! preferences: JSON lastUpdated: String! } ``` -------------------------------- ### Initial Federated GraphQL Schema Source: https://github.com/grafbase/extensions/blob/main/cli/postgres/README.md An initial GraphQL schema defining 'Post' and 'User' types, marked with `@key` directives for GraphQL federation. This schema outlines the structure before cross-database linking is configured. ```graphql type Post @key(fields: "id") { id: Int! title: String! authorId: Int! author: User } type User @key(fields: "id") { id: Int! name: String! } ``` -------------------------------- ### GraphQL Schema with Multiple Kafka Producers and Consumers Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md Shows how to reference multiple Kafka providers in the GraphQL schema for publishing and subscribing to different Kafka clusters. ```graphql schema @kafkaProducer(name: "prodEvents", provider: "production", topic: "events") @kafkaProducer( name: "analyticsEvents" provider: "analytics" topic: "analytics" ) { query: Query mutation: Mutation subscription: Subscription } type Mutation { logEvent(input: EventInput!): Boolean! @kafkaPublish(producer: "prodEvents") trackAnalytics(data: AnalyticsInput!): Boolean! @kafkaPublish(producer: "analyticsEvents") } type Subscription { productionEvents: Event! @kafkaSubscription(provider: "production", topic: "events") analyticsStream: Analytics! @kafkaSubscription(provider: "analytics", topic: "analytics") } ``` -------------------------------- ### GraphQL Mutation for Publishing Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md A GraphQL mutation query to trigger the publishing of a user event. It demonstrates how to pass arguments to the mutation, which are then used by the @kafkaPublish directive. ```graphql mutation PublishUserEvent($id: String!, $email: String!, $name: String!) { publishUserEvent( id: $id input: { email: $email, name: $name, eventType: "profile_update" } ) } ``` -------------------------------- ### NATS Extension Build Artifacts Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md Files generated in the `build` directory after successfully building the NATS extension from source. These include the Wasm component and manifest. ```text build/ ├── extension.wasm └── manifest.json ``` -------------------------------- ### Configure TLS with System CA Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md Sets up TLS configuration for a Kafka endpoint to use the system's trusted Certificate Authorities for verification. ```toml [[extensions.kafka.config.endpoint]] name = "default" bootstrap_servers = ["kafka.example.com:9092"] [extensions.kafka.config.endpoint.tls] system_ca = true ``` -------------------------------- ### Grafbase REST Directive Configuration Source: https://github.com/grafbase/extensions/blob/main/extensions/rest/README.md Provides an overview of the Grafbase REST extension's directives and their common configurations. This includes setting endpoints, HTTP methods, request bodies, and response selections. ```APIDOC @restEndpoint: Defines a named REST endpoint with a base URL and default headers. - name: string (required) - The name of the endpoint. - baseURL: string (required) - The base URL for the endpoint. - headers: [{ name: string, value: string }] (optional) - Default headers to send with requests. @rest: Applies to fields or mutations to define how to interact with a REST endpoint. - endpoint: string (required) - The name of the @restEndpoint to use. - http: { GET?: string, POST?: string, PUT?: string, DELETE?: string, PATCH?: string } (required) - Specifies the HTTP method and path. - Path can use template variables like "/users/{{ args.id }}". - POST/PUT/PATCH can include a `body` argument. - `body`: { static: object | selection: string } - Defines the request body. - `static`: A JSON object with static data. - `selection`: A GraphQL selection set to map data from input arguments. - selection: string (optional) - A GraphQL selection set to map the REST response to the field's type. ``` -------------------------------- ### Kafka Subscription with Dynamic Selection Filter Source: https://github.com/grafbase/extensions/blob/main/extensions/kafka/README.md Demonstrates using dynamic parameters within a JQ-style selection filter for Kafka subscriptions, allowing client-defined filtering criteria. ```graphql type Subscription { ordersAboveThreshold(minimumAmount: Float!): Order! @kafkaSubscription( topic: "orders" selection: "select(.amount > {{args.minimumAmount}})" ) } type Order { id: String! amount: Float! customerId: String! timestamp: String! } ``` -------------------------------- ### Grafbase gRPC Extension API Documentation Source: https://github.com/grafbase/extensions/blob/main/extensions/grpc/README.md Defines the schema directives and configuration for the Grafbase gRPC extension. This includes directives for linking extensions, defining protobuf messages, and defining protobuf services, as well as configuration for connecting to gRPC services. ```APIDOC Grafbase gRPC Extension Directives and Configuration: @grpcMethod(service: String!, method: String!, input: String = "*") - Directive used on GraphQL output fields to map them to gRPC methods. - Parameters: - service: The name of the gRPC service (e.g., "routeguide.RouteGuide"). - method: The name of the gRPC method (e.g., "GetFeature"). - input: The input type for the gRPC method. Can be "*" for the whole input or a specific transformation string. @protoMessages(definitions: [ProtoMessageDefinition]) - Directive to define Protocol Buffer message structures within the GraphQL schema. - Parameters: - definitions: An array of ProtoMessageDefinition objects. - ProtoMessageDefinition: - name: The name of the message (e.g., "Point"). - fields: An array of message fields. - name: Field name (e.g., "latitude"). - type: Field type (e.g., "int32", "string", "Point"). - number: Field number (e.g., 1). @protoServices(definitions: [ProtoServiceDefinition]) - Directive to define gRPC service definitions within the GraphQL schema. - Parameters: - definitions: An array of ProtoServiceDefinition objects. - ProtoServiceDefinition: - name: The fully qualified name of the gRPC service (e.g., "routeguide.RouteGuide"). - methods: An array of service methods. - name: Method name (e.g., "GetFeature"). - inputType: The name of the input message type (e.g., "Point"). - outputType: The name of the output message type (e.g., "Feature"). Gateway Configuration (TOML): [[extensions.grpc.config.services]] - Configuration block for defining gRPC service endpoints. - Properties: - name: The name of the gRPC service as defined in the schema (e.g., "routeguide.RouteGuide"). - address: The network address of the gRPC service (e.g., "http://routeguide.mydomain.local" or "{{ env.PRICING_SERVICE_URL }}"). Related Directives: - @link: Used to import extensions and their directives. - @protoMessages: Defines protobuf message structures. - @protoServices: Defines gRPC service and method signatures. Conventions: - Conversion between JSON and protobuf types follows the [ProtoJSON format](https://protobuf.dev/programming-guides/json/). Features: - Supports server streaming for subscription fields. - Supports client streaming (one message at a time). - Supports well-known protobuf types with ProtoJSON mapping (e.g., Value types, Duration, Empty, FieldMask). ``` -------------------------------- ### Entity Join: Configure Grafbase CLI Source: https://github.com/grafbase/extensions/blob/main/cli/postgres/README.md TOML configuration for the Grafbase CLI to specify column properties for the 'users' view in the 'public' schema. This ensures the 'id' column is correctly interpreted as non-nullable and unique for federation. ```toml [schemas.public.views.users.columns.id] nullable = false unique = true ``` -------------------------------- ### Load NATS Extension from Build Directory Source: https://github.com/grafbase/extensions/blob/main/extensions/nats/README.md Configuration to specify the local path to the built NATS extension artifacts (Wasm component and manifest) in your Grafbase Gateway configuration. ```toml [extensions.nats] path = "/path/to/build" ``` -------------------------------- ### Grafbase Postgres Extension Configuration Source: https://github.com/grafbase/extensions/blob/main/extensions/postgres/README.md Defines the configuration structure for the Postgres extension within `grafbase.toml`, including database connection details, pool settings, and TLS parameters. This section allows for connecting multiple databases and customizing connection pooling behavior. ```apidoc GrafbasePostgresExtensionConfig: # Optional: Specify the version of the extension or the path to a local build. # version: string # path: string # Configuration for connecting to Postgres databases. config: # Array of database configurations. databases: [ { # Optional: A name to link the database connection to a specific subgraph. # name: string # The connection URL for the Postgres database. # Use environment variables for sensitive parts like passwords. url: string # Connection pool configuration. pool: # Maximum number of connections in the pool (default: 10). # max_connections: integer # Minimum number of idle connections maintained (default: 0). # min_connections: integer # Maximum idle time before closing a connection (ms, default: 600000 / 10 min). # idle_timeout_ms: integer # Maximum time to wait for a connection from the pool (ms, default: 30000 / 30 sec). # acquire_timeout_ms: integer # Maximum lifetime of a connection (ms, default: 1800000 / 30 min). # max_lifetime_ms: integer } ] # TLS Configuration within the connection string: # For TLS connections, add parameters like: # sslmode=verify-full # sslrootcert=/path/to/ca.crt # sslcert=/path/to/client.crt # sslkey=/path/to/client.key ``` -------------------------------- ### GraphQL @grpcMethod Directive Usage Source: https://github.com/grafbase/extensions/blob/main/extensions/grpc/README.md Demonstrates how to use the @grpcMethod directive on a GraphQL output field to expose a gRPC service method. It specifies the gRPC service and method names, and optionally the input transformation. ```graphql type Query { getFeature(input: PointInput!): Feature @grpcMethod(service: "routeguide.RouteGuide", method: "GetFeature") } ``` -------------------------------- ### Configure Grafbase Gateway with Published Postgres Extension Source: https://github.com/grafbase/extensions/blob/main/extensions/postgres/README.md Specifies the desired version of the Postgres extension to be used by the Grafbase Gateway. This configuration is placed within the `grafbase.toml` file. ```toml # grafbase.toml [extensions.postgres] version = "0.5" ``` -------------------------------- ### Configure Global Schema Settings in TOML Source: https://github.com/grafbase/extensions/blob/main/cli/postgres/README.md Defines global settings for schema introspection, including table allowlists and denylists. These settings control which tables are included or excluded from GraphQL schema generation. ```toml enable_queries = true table_allowlist = null table_denylist = [] views = {} tables = {} ``` -------------------------------- ### Enable Query Logging Source: https://github.com/grafbase/extensions/blob/main/extensions/postgres/README.md Sets environment variables to enable query logging for the Grafbase extension at the debug level. This logs parameterized queries without revealing sensitive user data, useful for debugging database interactions. ```bash GRAFBASE_LOG=info,extension=debug ```