/Graphiti

Swift GraphQL Schema/Type framework for macOS and Linux

Primary LanguageSwiftMIT LicenseMIT

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: 1),
    ]
)

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) { _, _, _, _ in
            return "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 result = try schema.execute(request: query)
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.