• Stars
    star
    120
  • Rank 295,983 (Top 6 %)
  • Language
    Swift
  • License
    MIT License
  • Created about 8 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A GraphQL Client in Swift

AutoGraph

CocoaPods Compatible CircleCI

The Swiftest way to GraphQL

Features

AutoGraph is a Swift client framework for making requests using GraphQL and mapping the responses to strongly typed models. Models may be represented by any Decodable type. AutoGraph relies heavily on Swift's type safety to drive it, leading to safer, compile time checked code.

Requirements

Swift 5.3.2

  • Swift 5.2 iOS 10 - use version 0.14.7
  • Swift 5.1.3 iOS 10 - use version 0.11.1
  • Swift 5.0 iOS 8 - use version 0.10.0
  • Swift 5.0 pre Decodable - use version 0.8.0
  • Swift 4.2+ - use version 0.7.0.
  • Swift 4.1.2 - use version 0.5.1.

Platforms

  • iOS 10.0+
  • tvOS
  • watchOS
  • macOS 10.12+
  • Linux

Installation

CocoaPods

platform :ios, '10.0'
use_frameworks!

pod 'AutoGraph'

Swift Package Manager (SPM)

dependencies: [
.package(url: "https://github.com/remind101/AutoGraph.git", .upToNextMinor(from: "0.15.1"))
]

Code Generation

Code generation is in an early-alpha stage. If you're interested in testing it please open an inquiry.

Databases

Update

Previously this project would map into any arbitrary database directly via a database mapping library. In practice we've found that mapping to pure structs through Codable is simpler and enables more flexibility when combined with code generation. If you wish to still map directly to a database in the old style please use version 0.8.0. Going forward we are internally exploring different methods of code generation that enable flexible, code generated database caching behind the scenes. We hope to open source these efforts in the future, stay tuned.

Query Builder

AutoGraph includes a GraphQL query builder to construct queries in a type safe manner. However, using the query builder is not required; any object which inherits GraphQLQuery can act as a query. String inherits this by default.

Query Example

Raw GraphQL         AutoGraph
-----------         ---------
query MyCoolQuery {         AutoGraphQL.Operation(type: .query, name: "MyCoolQuery", fields: [
  user {                        Object(name: "user", fields: [
    favorite_authors {              Object(name: "favorite_authors", fields: [,
      uuid                              "uuid",
      name                              "name"
    }                               ]),
    uuid                            "uuid",
    signature                       "signature"
  }                             ])
}

Mutation Example

Raw GraphQL
-----------
mutation MyCoolMutation {
  updateFavoriteAuthor(uuid: "long_id", input: { name: "My Cool Name" })
  {
    favorite_author {
      uuid
      name
    }
  }
}

AutoGraph
---------
AutoGraphQL.Operation(type: .mutation, name: "MyCoolMutation", fields: [
                            Object(
                            name: "updateFavoriteAuthor",
                            arguments: [ // Continues "updateFavoriteAuthor".
                                "uuid" : "long_id",
                                "input" : [
                                   "name" : "My Cool Class"
                                ]
                            ],
                            fields: [
                                Object(
                                name: "favorite_author",
                                fields: [
                                    "uuid",
                                    "name"
                                    ])
                                ]
                        ])

Supports

Subscriptions

AutoGraph now supports subscriptions using the graphql-ws protocol. This is this same protocol that Apollo GraphQL server uses, meaning subscriptions will work with Apollo server.

let url = URL(string: "wss.mygraphql.com/subscriptions")!
let webSocketClient = try WebSocketClient(url: url)
webSocketClient.delegate = self   // Allows the user to inspect errors and events as they arrive.

let client = try AlamofireClient(url: AutoGraph.localHost,
                                 session: Session(configuration: MockURLProtocol.sessionConfiguration(),
                                                  interceptor: AuthHandler()))
let autoGraph = AutoGraph(client: client, webSocketClient: webSocketClient)

let request = FilmSubscriptionRequest()
let subscriber = self.subject.subscribe(request) { (result) in
    switch result {
    case .success(let object): // Handle new object.
    case .failure(let error):  // Handle error
    }
}

// Sometime later...
try autoGraph.unsubscribe(subscriber: subscriber!)

Decodable for type safe Models

AutoGraph relies entirely on Decodable for mapping GraphQL JSON responses to data models. It's as easy as conforming the model to Decodable!

JSONValue for type safe JSON

Behind the scenes AutoGraph uses JSONValue for type safe JSON. Feel free to import it for your own needs.

Threading

AutoGraph performs all network requests and mapping off of the main thread. Since a Request will eventually return whole models back to the caller on the main thread, it's important to consider thread safety with the model types being used. For this reason, using immutable struct types as models is recommended.

Network Library

AutoGraph currently relies on Alamofire for networking. However this isn't a hard requirement. Pull requests for this are encouraged!

Usage:

Request Protocol

  1. Create a class that conforms to the Request protocol. You can also extend an existing class to conform to this protocol. Request is a base protocol used for GraphQL requests sent through AutoGraph. It provides the following parameters.
    1. queryDocument - The query being sent. You may use the Query Builder or a String.
    2. variables - The variables to be sent with the query. A Dictionary is accepted.
    3. rootKeyPath - Defines where to start mapping data from. Empty string ("") will map from the root of the JSON.
    4. An associatedtype SerializedObject: Decodable must be provided to tell AutoGraph what data model to decode to.
    5. A number of methods to inform the Request of its point in the life cycle.
class FilmRequest: Request {
    /*
     query film {
        film(id: "ZmlsbXM6MQ==") {
            id
            title
            episodeID
            director
            openingCrawl
        }
     }
     */

    let query = Operation(type: .query,
                          name: "film",
                          fields: [
                            Object(name: "film",
                                   alias: nil,
                                   arguments: ["id" : "ZmlsbXM6MQ=="],
                                   fields: [
                                    "id",  // May use string literal or Scalar.
                                    Scalar(name: "title", alias: nil),
                                    Scalar(name: "episodeID", alias: nil),
                                    Scalar(name: "director", alias: nil),
                                    Scalar(name: "openingCrawl", alias: nil)])
                            ])

    let variables: [AnyHashable : Any]? = nil

    let rootKeyPath: String = "data.film"

    public func willSend() throws { }
    public func didFinishRequest(response: HTTPURLResponse?, json: JSONValue) throws { }
    public func didFinish(result: Result<Film, Error>) throws { }
}

Sending

Swift

  1. Call send on AutoGraph
    1. autoGraph.send(request, completion: { [weak self] result in ... }
  2. Handle the response
    1. result is a generic Result<SerializedObject, Error> enum with success and failure cases.

Objective-C

Sending via Objective-C isn't directly possible because of AutoGraph's use of associatedtype and generics. It is possible to build a bridge(s) from Swift into Objective-C to send requests.

Contributing

  • Open an issue if you run into any problems.

Pull Requests are welcome!

  • Open an issue describing the feature add or problem being solved. An admin will respond ASAP to discuss the addition.
  • You may begin working immediately if you so please, by adding an issue it helps inform others of what is already being worked on and facilitates discussion.
  • Fork the project and submit a pull request. Please include tests for new code and an explanation of the problem being solved. An admin will review your code and approve it before merging.
  • Keep LinuxTests up-to-date swift test --generate-linuxmain
  • If you see an error like this while building from the command line could not build Objective-C module try prepending commands with xcrun -sdk macosx

License

The MIT License (MIT)

Copyright (c) 2017-Present Remind101

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

empire

A PaaS built on top of Amazon EC2 Container Service (ECS)
Go
2,688
star
2

assume-role

Easily assume AWS roles in your terminal.
Go
566
star
3

android-arch-sample

Sample app for MVP Architecture on Android
Java
348
star
4

ssm-env

Expand env variables from AWS Parameter Store
Go
251
star
5

tugboat

Rest API and AngularJS client for deploying github repos.
Go
235
star
6

conveyor

A fast build system for Docker images.
Go
221
star
7

slashdeploy

GitHub Deployments for Slack
JavaScript
153
star
8

deploy

CLI for GitHub Deployments
Go
134
star
9

jest-transform-graphql

Make .graphql file importing work in Jest
JavaScript
121
star
10

rest-graphql

Middleware for Express to adapt REST requests to GraphQL queries
JavaScript
55
star
11

angular-tooltip

Simple and extensible tooltips for angularjs
JavaScript
41
star
12

migrate

Simple migrations for database/sql
Go
40
star
13

stacker_blueprints

DEPRECATED - moved to:
Python
39
star
14

emp

[DEPRECATED] Command line interface for Empire
Go
37
star
15

mq-go

SQS Consumer Server for Go
Go
28
star
16

dbsnap

Tool to copy and verify AWS RDS snapshots.
Python
24
star
17

pkg

A layer of convenience over the Go stdlib
Go
22
star
18

newrelic

DEPRECATED: Use the official lib here https://github.com/newrelic/go-agent
Go
19
star
19

logspout-kinesis

A Logspout adapter for writing logs to Amazon Kinesis
Go
16
star
20

request_id

Middleware for logging heroku request id's
Ruby
16
star
21

exceptions

A Ruby gem for tracking exceptions.
Ruby
15
star
22

grape-pagination

Pagination helpers for Grape.
Ruby
14
star
23

dockerstats

Easy scraping for the Docker stats api.
Go
14
star
24

auto-value-realm

An extension for Google's AutoValue that allows using Realm's datastore
Java
13
star
25

ecsdog

[DEPRECATED] ECS events are now automatically pulled in with the AWS integration
Go
10
star
26

kinesumer

Kinesis consumer library in Go
Go
10
star
27

turbolinks-redirect

Simple redirect_to support for turbolinks and jquery-rails.
Ruby
9
star
28

docker-build

A small script for building, tagging and pushing Docker images
Shell
9
star
29

dnsdog

DNS metrics in DataDog
Go
9
star
30

empire_ami

Home of the AMI building tools for the Official Empire AMI
Shell
9
star
31

policies

Remind Privacy Policy & Terms of Service from www.remind.com
7
star
32

collective

[DEPRECATED use https://github.com/remind101/r101-datadog instead] It collects metrics and puts it on STDOUT.
Ruby
6
star
33

hubot-deploy

Hubot script for GitHub Deployments.
CoffeeScript
6
star
34

reInvent-2015

Slides and Demo resources for Docker & ECS in Production talk.
Go
4
star
35

ruby-cloud-profiler

Ruby
3
star
36

capybara-mocktime

Ruby gem for synchronizing time between tests and the browser using Timecop and Sinon.
Ruby
3
star
37

activerecord-poro

Associations for plain old ruby objects
Ruby
3
star
38

AutoGraphParser

Swift GQL Parser
Swift
3
star
39

homebrew-formulae

Homebrew tap for Remind tools and utilities.
Ruby
3
star
40

formatted-metrics

Easily produce metrics for consumption by l2met.
Ruby
3
star
41

acme-inc

An app that does nothing.
Go
2
star
42

kinesis

Go program and library for streaming to Amazon Kinesis.
Go
2
star
43

gopheragent

A golang user-agent parser
Go
2
star
44

dockerdog

Better Docker event metrics for DataDog
Go
2
star
45

share-on-remind-extension

Share on Remind Extension
JavaScript
2
star
46

git-deploy

Ruby
2
star
47

amazon-ecs-agent

The official Amazon ECS Agent, with some Remind/Empire specific patches applied.
Makefile
2
star
48

activerecord-pgbouncer

ActiveRecord connection adapter for using PgBouncer safely.
Ruby
2
star
49

cloudsns

SNS polling library for cloudformation events
Python
2
star
50

action-require-reviewer

Github workflow action to require a reviewer on pushed branches
TypeScript
1
star
51

metrics

Go library for printing metrics in an l2met compatible format.
Go
1
star
52

e164.rb

e164.js but ruby
Ruby
1
star
53

all_my_circuits

Mostly threadsafe implementation of the CircuitBreaker pattern for Ruby.
Ruby
1
star
54

migrate_safely

Adds confirmation prompt for rake db:migrate
Ruby
1
star
55

beso

Ruby
1
star
56

pooled-redis

Connection pooled Redis client that utilizes promises.
JavaScript
1
star
57

AutoGraphCodeGen

Swift GraphQL Code Generator
Swift
1
star
58

email-provider

Give it an email address, and get the email provider back.
Ruby
1
star