Skip to content

Swift GraphQL Schema/Type framework for macOS and Linux

License

Notifications You must be signed in to change notification settings

noahemmet/Graphiti

 
 

Repository files navigation

Graphiti

Graphiti is a Swift library for building GraphQL schemas/types fast, safely and easily.

Swift License Slack Travis Codecov Codebeat

Looking for help? Find resources from the community.

Getting Started

An overview of GraphQL in general is available in the README for the Specification for GraphQL. That overview describes a simple set of GraphQL examples that exist as tests in this repository. A good way to get started with this repository is to walk through that README and the corresponding tests in parallel.

Using Graphiti

Add Graphiti to your Package.swift

import PackageDescription

let package = Package(
    dependencies: [
        .Package(url: "https://github.com/GraphQLSwift/Graphiti.git", majorVersion: 0, minor: 6),
    ]
)

Graphiti provides two important capabilities: building a type schema, and serving queries against that type schema.

First, build a Graphiti type schema which maps to your code base.

let schema = try Schema<Void> { schema in
    schema.query { query in
        try query.field(name: "hello", type: String.self) { (_, _, _, eventLoop, _) in
            return eventLoop.next().newSucceededFuture(result: "world")
        }
    }
}

This defines a simple schema with one type and one field, that resolves to a fixed value. More complex examples are included in the Tests directory.

Then, serve the result of a query against that type schema.

let query = "{ hello }"
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let result = try schema.execute(request: query, eventLoopGroup: eventLoopGroup).wait()
try eventLoopGroup.syncShutdownGracefully()
print(result)

Output:

{
    "data": {
        "hello": "world"
    }
}

This runs a query fetching the one field defined. The execute function will first ensure the query is syntactically and semantically valid before executing it, reporting errors otherwise.

let query = "{ boyhowdy }"
let result = try schema.execute(request: query)
print(result)

Output:

{
    "errors": [
        {
            "locations": [
                {
                    "line": 1,
                    "column": 3
                }
            ], 
            "message": "Cannot query field \"boyhowdy\" on type \"Query\"."
        }
    ]
}

License

This project is released under the MIT license. See LICENSE for details.

About

Swift GraphQL Schema/Type framework for macOS and Linux

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Swift 100.0%