Skip to content

GraphQLSwift/graphql-vapor

Repository files navigation

GraphQLVapor

WARNING: This package is in v0.x beta. It's API is still evolving and is subject to breaking changes in minor version bumps.

A Swift library for integrating GraphQL with Vapor, enabling you to easily expose GraphQL APIs in your Vapor applications.

Features

Installation

Add GraphQLVapor as a dependency in your Package.swift:

dependencies: [
    .package(url: "https://github.com/NeedleInAJayStack/graphql-vapor.git", from: "1.0.0"),
]

Then add it to your target:

.target(
    name: "YourTarget",
    dependencies: [
        .product(name: "GraphQLVapor", package: "graphql-vapor"),
    ]
)

Usage

Basic Example

import GraphQL
import GraphQLVapor
import Vapor

// Define your GraphQL schema
// To construct schemas, consider using `Graphiti` or `graphql-generator`
let schema = try GraphQLSchema(
    query: GraphQLObjectType(
        name: "Query",
        fields: [
            "hello": GraphQLField(
                type: GraphQLString,
                resolve: { _, _, _, _ in
                    "World"
                }
            )
        ]
    )
)

// Define your Context
struct GraphQLContext: Sendable {}

// Register GraphQL to the Vapor Application
app.graphql(schema: schema) { _ in
    return GraphQLContext()
}

Now just run the application! You can view the GraphiQL IDE at /graphql, or query directly using GET or POST:

curl -X POST http://localhost:8080/graphql \
  -H "Content-Type: application/json" \
  -d '{"query": "{ hello }"}'

Response:

{
  "data": {
    "hello": "World"
  }
}

See the RouteBuilder.graphql function documentation for advanced configuration options.

Computing GraphQL Context

The required closure in the graphql function is used to compute the GraphQLContext object, which is injected into each GraphQL resolver. The inputs argument passes in data from the request so that the Context can be created dynamically:

app.graphql(schema: schema) { inputs in
    return GraphQLContext(
        userID: inputs.vaporRequest.auth.userID,
        logger: inputs.vaporRequest.logger,
        debug: inputs.vaporRequest.headers[.init("debug")!] != nil,
        operationName: inputs.graphQLRequest.operationName
    )
}