• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

GraphQLSwift/Graphiti: The Swift GraphQL Schema framework for macOS and Linux

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

GraphQLSwift/Graphiti

开源软件地址(OpenSource Url):

https://github.com/GraphQLSwift/Graphiti

开源编程语言(OpenSource Language):

Swift 100.0%

开源软件介绍(OpenSource Introduction):

Graphiti

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

Swift License Slack GitHub Actions Maintainability Coverage

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", .upToNextMinor(from: "0.20.1")),
    ]
)

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

Defining entities

First, we declare our regular Swift entities.

struct Message : Codable {
    let content: String
}

⭐️ One of the main design decisions behind Graphiti is not to polute your entities declarations. This way you can bring your entities to any other solution with ease.

Defining the context

Second step is to create your application's context. The context will be passed to all of your field resolver functions. This allows you to apply dependency injection to your API. This is the place where you can put code that talks to a database or another service.

struct Context {
    func message() -> Message {
        Message(content: "Hello, world!")
    }
}

⭐️ Notice again that this step doesn't require Graphiti. It's purely business logic.

Defining the GraphQL API resolver

Now that we have our entities and context we can create the GraphQL API resolver.

import Graphiti

struct Resolver {
    func message(context: Context, arguments: NoArguments) -> Message {
        context.message()
    }
}

Defining the GraphQL API schema

Now we can finally define the GraphQL API with its schema.

struct MessageAPI : API {
    let resolver: Resolver
    let schema: Schema<Resolver, Context>
    
    init(resolver: Resolver) throws {
        self.resolver = resolver

        self.schema = try Schema<Resolver, Context> {
            Type(Message.self) {
                Field("content", at: \.content)
            }

            Query {
                Field("message", at: Resolver.message)
            }
        }
    }
}

⭐️ Notice that API allows dependency injection. You could pass mocks of resolver and context when testing, for example.

Querying

To query the schema we need to instantiate the api and pass in an EventLoopGroup to feed the execute function alongside the query itself.

import NIO

let resolver = Resolver()
let context = Context()
let api = try MessageAPI(resolver: resolver)
let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
        
defer {
    try? group.syncShutdownGracefully()
}

api.execute(
    request: "{ message { content } }",
    context: context,
    on: group
).whenSuccess { result in
    print(result)
}

The output will be:

{"data":{"message":{"content":"Hello, world!"}}}

API.execute returns a GraphQLResult which adopts Encodable. You can use it with a JSONEncoder to send the response back to the client using JSON.

Async resolvers

To use async resolvers, just add one more parameter with type EventLoopGroup to the resolver function and change the return type to EventLoopFuture<YouReturnType>. Don't forget to import NIO.

import NIO

struct Resolver {
    func message(context: Context, arguments: NoArguments, group: EventLoopGroup) -> EventLoopFuture<Message> {
        group.next().makeSucceededFuture(context.message())
    }
}

Subscription

This library supports GraphQL subscriptions. To use them, you must create a concrete subclass of the EventStream class that implements event streaming functionality.

If you don't feel like creating a subclass yourself, you can use the GraphQLRxSwift repository to integrate RxSwift observables out-of-the-box. Or you can use that repository as a reference to connect a different stream library like ReactiveSwift, OpenCombine, or one that you've created yourself.

Star Wars API example

Check the Star Wars API for a more complete example.

License

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




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap