Code Monkey home page Code Monkey logo

swift-graphql's Introduction

A GraphQL client that lets you forget about GraphQL.

CI Tests

www.swift-graphql.com

Features

  • Intuitive: You'll forget about the GraphQL layer altogether.
  • 🏖 Time Saving: I've built it so you don't have to waste your precious time.
  • ☝️ Generate once: Only when your schema changes.
  • ☎️ Subscriptions: Listen to subscriptions using webhooks.
  • 🏔 High Level: You don't have to worry about naming collisions, variables, anything. Just Swift.

Overview

SwiftGraphQL is a GraphQL Client that ships with a type-safe query builder. It lets you perform queries, mutations and listen for subscriptions. The query builder guarantees that every query you can create is valid and complies with the GraphQL spec.

The library is centered around three core principles:

  • 🚀 If your project compiles, your queries work.
  • 🦉 Use Swift in favour of GraphQL wherever possible.
  • 🕊 Packages shouldn't lock you in to the "framework".

You can use only parts of SwiftGraphQL that are useful to you (e.g. use GraphQLWebSocket implementation but not the query builder, or WebSocket but not the client).

Documentation

You can find detailed documentation on the SwiftGraphQL page at www.swift-graphql.com.

Examples

You can find examples of how to use a local GraphQL API or remote one in the /examples directory.

  • thesocialnetwork - a simple chat app that shows how to swift-graphql with queries and subscriptions,
  • GitHubStars - shows how to use GitHub API with swift-graphql.

Other Libraries

SwiftGraphQL solves a set of specific problems but it doesn't solve every problem. Depending on your needs, you may also want to check out


Thank you

I would like to dedicate this last section to everyone who helped develop this library.

  • First, I would like to thank Dillon Kearns, the author of elm-graphql, who inspired me to write the library, and helped me understand the core principles behind his Elm version.
  • Second, I would like to thank Peter Albert for giving me a chance to build this library, having faith that it's possible, and all the conversations that helped me push through the difficult parts of it.
  • Thirdly, special thanks to Phil Pluckthun who explained all the bits of how urql and wonka work,
  • Fourthly, thanks to Orta Therox for helping me navigate Combine.
  • Lastly, I'd like to thank every contributor to the project. SwiftGraphQL is better because of you. Thank you!

Thank you! 🙌


License

MIT @ Matic Zavadlal

swift-graphql's People

Contributors

amzd avatar antonnyman avatar barnard-b avatar bradleyrzeller avatar codifilo avatar cooperwolfe avatar dato avatar dimamachina avatar fedos avatar github-actions[bot] avatar idiomatic avatar keuha avatar lromyl avatar marmarelis avatar maticzav avatar pabloszx avatar pokryfka avatar robsontenorio avatar rushairer avatar shaps80 avatar singingwolfboy avatar sundea avatar tamc avatar teddy-bersentes avatar yiyingzz avatar yonaskolb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swift-graphql's Issues

No such module 'Combine'

Describe the bug
The project does not compile under Release configuration. The error occurs in SwiftGraphQL lib, HTTP.swift file.

Screenshots
Screen Shot 2021-02-22 at 19 12 49

Desktop (please complete the following information):

  • SwiftGraphQL 2.0.0
  • XCode Version 12.4 (12D4e)
  • Min iOS target 13.0

Additional context
The app compiles if Debug configuration is used.

Maybe my target configuration is incorrect? Although the project is fairly new and I did not make any changes to the default project settings.

GraphQL: SDL Support

Describe the bug
I've downloaded the Github schema by link https://docs.github.com/en/graphql/overview/public-schema and then have tried to run the generator % swift-graphql schema.docs.graphql and it has failed

To Reproduce
Steps to reproduce the behavior:

  1. Go to 'https://docs.github.com/en/graphql/overview/public-schema' and download the schema
  2. run % swift-graphql schema.docs.graphql
  3. See error
Generating SwiftGraphQL Selection 🚀
⠋ Fetching GraphQL SchemaThe data couldn’t be read because it isn’t in the correct format.
Error: Couldn't reach GraphQL server at given endpoint.

Error "Must be leaf type" in listValue

Describe the bug
Getting error "must be leaf type" in list value for input

Query:
query listQueryByRange($fromDT: String!, $toDT: String!) {
listValueQuery(startAt: {range: [$fromDT, $toDT]}}) {

}}

Declaration in Graphiti:
InputField("startAt", at: .startAt, as: TypeReference.self)

extension SearchableDateFilterInput:Codable {

enum CodingKeys: String, CodingKey {
    case range
}
public func encode(to encoder: Encoder) throws {
    try container.encode(range, forKey: .range)
}

public init(from decoder: Decoder) throws {
    self.init(range: nil)
    range = try values.decodeIfPresent([String].self, forKey: .range)
    
}

}

To Reproduce
Steps to reproduce the behavior:

  1. Apply below query
    query listQueryByRange($fromDT: String!, $toDT: String!) {
    listValueQuery(startAt: {range: [$fromDT, $toDT]}}) {

}}

Expected behavior
Should execute the query and must not throw the error "must be leaf type"

Cannot convert value of type 'String?' to type 'OptionalArgument<String>'

Describe the bug
A clear and concise description of what the bug is.

Forced to cast optional values with OptionalArgument(some-value) instead of being able to pass swift optionals directly inside of Selection.Mutation's

The Error(s):
Cannot convert value of type 'String?' to expected argument type 'OptionalArgument<String>' or Cannot convert value of type '[String]?' to expected argument type 'OptionalArgument<[String]>' when trying to pass optional values to a Selection.Mutation

To Reproduce
Steps to reproduce the behavior:

struct UserDao: Identifiable {
  let id: String
  let name: String?
}

struct CreateUser {
  let user: UserDao
  let errors: [String]
}

struct UserForm {
  let id: String
  let name: String?
}

private static func userSelection() -> Selection<UserDao, Objects.User> {
    return  Selection.User {
      UserDao(id: try $0.id(), name: try $0. name())
  }
}

static func updateUser(form: UserForm) {
   let user = userSelection()

   let updateUser = Selection.UpdateUserPayload { u in
      CreateUser(user: try u.user(selection: user), errors: try u.errors())
   }

  // Name errors here
  let query = Selection.Mutation {
      try $0.updateUser(id: form.id, name: name, selection: updateUser.nullable)
  }

  // If changed to below it will work fine:
  let name = OptionalArgument(form.name)
  let query2 = Selection.Mutation {
       try $0.updateUser(id: form.id, name: name, selection: updateUser.nullable)
   }
}

Expected behavior
Expect to be able to pass swift optional types directly into the Selection Mutation without conversion.

Screenshots
n/a

Smartphone (please complete the following information):

  • Device: iPhone 12 simulator
  • OS: iOS 12
  • Browser: n/a
  • Version n/a

Additional context
Maybe this is working as intended and should be a feature request/enhancement

StringIndexValidation.swift:120: Fatal error: String index is out of bounds

Hi!
I need help, an idea of what can be wrong with schema.

I installed the tool using brew
then I tried to generate a code for my local graphql server
code generation fails

SwiftGraphQL % swift-graphql http://127.0.0.1:3001/graphql --output ./output
Generating SwiftGraphQL Selection 🚀
✔ Schema loaded!
⠋ Generating APISwift/StringIndexValidation.swift:120: Fatal error: String index is out of bounds

I am not common with /graphql endpoint protocol and it might be the server setup is not right. I managed to use it with apollo but there can be a hidden issue.
I get the error During the code generation phase
I attached schemas from the playground to the issues. it might be connected to this part that autogenerated by Apollo for some reason

# The `Upload` scalar type
 represents a file upload.
scalar Upload

To Reproduce
Steps to reproduce the behavior:

  1. clone https://github.com/kanstantsin-bucha/swift-playgrounds
  2. navigate to _GraphQL/graphql-apollo-api-part1
  3. run npm start
  4. run swift-graphql http://127.0.0.1:3001/graphql --output ./output

Expected behavior
Code is generated.

Desktop (please complete the following information):

Why not use dataTaskPublisher

I see that you have Combine as a dependency in the HTTP module and yet you are not using URLSession#dataTaskPublisher(for:) and rely on callbacks. Would be awesome to have AnyPublisher<Value, Error> returned from HTTP#send

Conflicting package dependency (Yams) in case of SwiftLint plugin

Describe the bug
The currently used Yams dependency conflicts in case of using the latest swiftLint dependency in the same swift package to enable as build-plugin

error project: Failed to resolve dependencies Dependencies could not be resolved because root depends on 'swift-graphql' 4.0.0..<5.0.0 and root depends on 'swiftlint' 0.49.1..<1.0.0.
'swiftlint' is incompatible with 'swift-graphql' because 'swift-graphql' 4.0.0 depends on 'yams' 4.0.4..<5.0.0 and no versions of 'swift-graphql' match the requirement 4.0.1..<5.0.0.
'swiftlint' >= 0.49.1 practically depends on 'yams' 5.0.1..<6.0.0 because 'swiftlint' 0.49.1 depends on 'yams' 5.0.1..<6.0.0 and no versions of 'swiftlint' match the requirement 0.49.2..<1.0.0.

To Reproduce
Steps to reproduce the behavior:

  1. Create new Package
  2. add package dependencies for swift-graphql (4.0.0) and SwiftLint (0.49.1) to enable SwiftLintPlugin as build-plugin on target
	.package(
	   url: "https://github.com/maticzav/swift-graphql",
	   from: "4.0.0"
	),
	.package(
	   url: "https://github.com/realm/SwiftLint",
	   from: "0.49.1"
	)
  1. Resolve dependencies
  2. See error above

Expected behavior
Updating the Yams dependency within the swift-graphql Package.swift to the latest major (5) would solve the conflict of incompatible swiftLint versions

.package(url: "https://github.com/jpsim/Yams.git", from: "5.0.0"),

The only requirement for the major bump of the YAMS is the minimum swift tools version of 5.3 which is the case for swift-graphql

Environment (please complete the following information):

  • OS: macOS 12.6, iOS 16
  • Xcode version: 14.0.1
  • Swift tools version: 5.7

Additional context
If there might be an update of the Yams dependency, I'd appreciate any consideration of updating other third party dependencies as e.g. Spinner to the respective major version (2) as well.
.package(url: "https://github.com/dominicegginton/Spinner", from: "2.0.0")

Cannot download Schema from CLI

Describe the bug

trying to use the CLI, but only getting a Unknown: StatusCode error

To Reproduce

swift-graphql https://api.komoot.de/graphql/v1/sdl -o ./ --config swiftgraphql.yml

Error: statusCode

where swiftgraphql.yml = swiftgraphql.txt

scalars:
  Long: Double
  ZonedDateTime: DateTime

Expected behavior
A more verbose Error :D
or even better, it downloading the schema :D

multi-line descriptions break the generator

Describe the bug
Apollo GraphQL allows something like this:

    """
    Establish permissions the user might have for the bike.

    Used for FW variant "abc"
    """
    bikePermission(
      id: String!
    ): BikeConnectResult

The generator outputs the above as:

/// Establish permissions the user might have for the bike.

    Used for FW variant "abc"

    func bikePermission<Type>(id: String, selection: Selection<Type, Unions.BikeConnectResult?>) throws -> Type {

Expected behavior
Multi-line docs are supported and do not create an uncompilable code

Support for CocoaPods

Is your feature request related to a problem? Please describe.

We are unable to use SPM in our project so we would like to use this framework over CocoaPods

Describe the solution you'd like
Publish the framework on CocoaPods

Discussion: Subscriptions

This project looks very good and I'd love to use it but I also need subscriptions.

Did you already have a rough idea on how to implement this? So I am not doing the same work twice.

Interfaces shouldn't require each interface implementer to be present on selection building

Describe the bug

BrainTree overloads their 'node' interface to cover basically everything under the sun. And going through the node interface is the only way to query for updates on those implementers.

Is this the way?

image

Here is a link to their docs:

https://braintree.gitbook.io/in-store/guides/making-a-transaction#checking-the-reader-charge-status

Steps to Reproduce

Create an API with a node interface.
Then build several objects that implement that interface.
Then add a query through the node interface.
Now build a query for one of the node interfaces.

Expected behavior

All arguments should be optional, with only one required

I expect that there is probably a better way to do this but I couldn't figure it out from the docs and my laptop is struggling with the generated api.

The "data" field was excluded, it throw ObjectDecodingError.unexpectedObjectType

In my graphql api, if return errors, "data" field will be excluded,

SwiftGraphQLClient/Client/Selection.swift

 125           let data = try selection.decode(raw: self.data)

self.data is nill , will throw an error:

throw ObjectDecodingError.unexpectedObjectType(
                    expected: "Dictionary",
                    received: codable.value
                )

I don't agree with this method. self.data == nil should be skipped to
Keep the errors from graphql api.

Originally posted by @rushairer in #99 (comment)

Brew tap is failing

@maticzav The project looks super promising and I'm so excited to give it a try! Wanted to thank you for putting so much effort into it! ❤️

When following the README Brew install instructions I'm getting an error:

$ brew tap maticzav/swift-graphql https://github.com/maticzav/swift-graphql.git
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/cask).
==> Updated Casks
Updated 1 cask.

==> Tapping maticzav/swift-graphql
Cloning into '/usr/local/Homebrew/Library/Taps/maticzav/homebrew-swift-graphql'...
remote: Enumerating objects: 25, done.
remote: Counting objects: 100% (25/25), done.
remote: Compressing objects: 100% (17/17), done.
remote: Total 2135 (delta 6), reused 16 (delta 6), pack-reused 2110
Receiving objects: 100% (2135/2135), 10.54 MiB | 1.82 MiB/s, done.
Resolving deltas: 100% (1181/1181), done.
Error: Invalid formula: /usr/local/Homebrew/Library/Taps/maticzav/homebrew-swift-graphql/Formula/SwiftGraphQL.rb
No available formula with the name "SwiftGraphQL".
In formula file: /usr/local/Homebrew/Library/Taps/maticzav/homebrew-swift-graphql/Formula/SwiftGraphQL.rb
Expected to find class Swiftgraphql, but only found: SwiftGraphQL.
Error: Cannot tap maticzav/swift-graphql: invalid syntax in tap!

Looks like some funny Ruby problem: Expected to find class Swiftgraphql, but only found: SwiftGraphQL.

I'm on macOS Catalina 10.15.7.

$ brew --version
Homebrew 3.0.1-74-g74fd6c8
Homebrew/homebrew-core (git revision b9a6fd6; last commit 2021-02-16)
Homebrew/homebrew-cask (git revision 10dc6a; last commit 2021-02-16)

Generator butchers type names in some cases

Describe the bug

enum TypeName: String, Codable {
   case firmwareNrfmTadata = "FirmwareNRFMetadata"
}

Why not preserve the name as it is?

I've also noticed this (which is not as bad as the first example):

func dateIso() throws -> String {
        let field = GraphQLField.leaf(
            name: "dateISO",
            arguments: []
        )
       ...
}

Using names like dateISO or FirmwareNRFMetadata is a pretty standard convention in the Swift world, as far as I know...

ObjectDecodingError.unexpectedObjectType on nullable field

Hi,

Upgraded to version 4.0.0 and having issues with one of my queries now.

Query code:

struct Recording {
    struct Analysis {
        let success: Bool
    }
    
    let id: String
    let recordingStartedAt: Int?
    let analysis: Analysis?
}

let analysisSelection = Selection.Analysis<Recording.Analysis> {
    let success = try $0.success()
    
    return Recording.Analysis(success: success)
}

let recordingSelection = Selection.Recording<Recording> {
    let id = try $0.id()
    let recordingStartedAt = try $0.recordingStartedAt()
    let analysis = try $0.analysis(selection: analysisSelection.nullable)
    
    return Recording(id: id,
                     recordingStartedAt: recordingStartedAt,
                     analysis: analysis)
}

let query = Selection.Query {
    try $0.getMyRecordings(selection: recordingSelection.nullable.list)
}

Raw query response looks like this:

"getMyRecordingsquery__mmn5vco4e5qa":
	[[
		"__typename": "Recording",
		"idrecording__mmn5vco4e5qa": "628fc124bb23b25b368474cf",
		"analysisrecording__mmn5vco4e5qa": <null>,
		"recordingStartedAtrecording__mmn5vco4e5qa": <null>
	]]

However, I'm receiving ObjectDecodingError.unexpectedObjectType (expected : "Dictionary", received : <null>) on .sink(receiveCompletion:). After some debugging it looks like it's caused by decoding "analysisrecording__mmn5vco4e5qa", the decoder still invokes analysisSelection even if the object is <null>.

Maybe I'm missing something here?

Thanks!

Expose a boolean `mock` property in selection

Right now, it's hard to verify data in the query when data contains a particular format of

  • a string (URL for example),
  • an array (might be a non-empty array),
  • optional value (might always be there).

To consider the problem, we should expose a $0.decoding boolean value that is false when the query is building and true when we are actually decoding the data.

Create a generator executable

We should have a simple to use executable that would let developers use SwiftGraphQL without setting up a separate project.

This way, developers could also skip the build phase script altogether.

Can not install on Ventura

Describe the bug
Running brew install SwiftGraphQL fails.

To Reproduce
Steps to reproduce the behavior:

  1. Go to terminal
  2. Run brew tap maticzav/swift-graphql https://github.com/maticzav/swift-graphql.git
  3. Run brew install SwiftGraphQL
  4. See error

Expected behavior
Expect it to install SwiftGraphQL.

Screenshots

brew install SwiftGraphQL
==> Fetching maticzav/swift-graphql/swiftgraphql
==> Downloading https://github.com/maticzav/swift-graphql/archive/4.1.0.tar.gz
Already downloaded: /Users/name/Library/Caches/Homebrew/downloads/2649c5418a1dc49aaa341e1192520386027296e1ea5b5030195a9a8e5494e223--swift-graphql-4.1.0.tar.gz
==> Installing swiftgraphql from maticzav/swift-graphql
==> make install PREFIX=/opt/homebrew/Cellar/swiftgraphql/4.1.0
Last 15 lines from /Users/name/Library/Logs/Homebrew/swiftgraphql/01.make:
make
install
PREFIX=/opt/homebrew/Cellar/swiftgraphql/4.1.0

swift build --disable-sandbox -c release --product swift-graphql
warning: /Users/name/Library/org.swift.swiftpm/configuration is not accessible or not writable, disabling user-level configuration features.
warning: /Users/name/Library/org.swift.swiftpm/security is not accessible or not writable, disabling user-level security features.
warning: /Users/name/Library/Caches/org.swift.swiftpm is not accessible or not writable, disabling user-level cache features.
warning: 'swift-graphql-4.1.0': failed loading cached manifest for 'swift-graphql-4.1.0': Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “manifests” in the folder “org.swift.swiftpm”." UserInfo={NSFilePath=/Users/name/Library/Caches/org.swift.swiftpm/manifests, NSUnderlyingError=0x6000022604b0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
warning: 'swift-graphql-4.1.0': failed closing cache: Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “manifests” in the folder “org.swift.swiftpm”." UserInfo={NSFilePath=/Users/name/Library/Caches/org.swift.swiftpm/manifests, NSUnderlyingError=0x6000022619e0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
error: 'swift-graphql-4.1.0': Invalid manifest
/private/tmp/swiftgraphql-20230303-12254-bsxajz/swift-graphql-4.1.0/Package.swift:3:8: error: no such module 'PackageDescription'
import PackageDescription
       ^
make: *** [build] Error 1

If reporting this issue please do so to (not Homebrew/brew or Homebrew/homebrew-core):
  maticzav/swift-graphql

/opt/homebrew/Library/Homebrew/utils/github/api.rb:315:in `raise_error': Validation Failed: [{"message"=>"The listed users and repositories cannot be searched either because the resources do not exist or you do not have permission to view them.", "resource"=>"Search", "field"=>"q", "code"=>"invalid"}] (GitHub::API::ValidationFailedError)
	from /opt/homebrew/Library/Homebrew/utils/github/api.rb:241:in `open_rest'
	from /opt/homebrew/Library/Homebrew/utils/github.rb:190:in `search'
	from /opt/homebrew/Library/Homebrew/utils/github.rb:194:in `search_results_items'
	from /opt/homebrew/Library/Homebrew/utils/github.rb:40:in `search_issues'
	from /opt/homebrew/Library/Homebrew/utils/github.rb:84:in `issues_for_formula'
	from /opt/homebrew/Library/Homebrew/exceptions.rb:498:in `fetch_issues'
	from /opt/homebrew/Library/Homebrew/exceptions.rb:493:in `issues'
	from /opt/homebrew/Library/Homebrew/exceptions.rb:549:in `dump'
	from /opt/homebrew/Library/Homebrew/brew.rb:150:in `rescue in <main>'
	from /opt/homebrew/Library/Homebrew/brew.rb:138:in `<main>'
/opt/homebrew/Library/Homebrew/formula.rb:2538:in `block in system': Failed executing: make install PREFIX=/opt/homebrew/Cellar/swiftgraphql/4.1.0 (BuildError)
	from /opt/homebrew/Library/Homebrew/formula.rb:2474:in `open'
	from /opt/homebrew/Library/Homebrew/formula.rb:2474:in `system'
	from /opt/homebrew/Library/Taps/maticzav/homebrew-swift-graphql/Formula/swiftgraphql.rb:16:in `install'
	from /opt/homebrew/Library/Homebrew/build.rb:177:in `block (3 levels) in install'
	from /opt/homebrew/Library/Homebrew/utils.rb:606:in `with_env'
	from /opt/homebrew/Library/Homebrew/build.rb:139:in `block (2 levels) in install'
	from /opt/homebrew/Library/Homebrew/formula.rb:1325:in `block in brew'
	from /opt/homebrew/Library/Homebrew/formula.rb:2705:in `block (2 levels) in stage'
	from /opt/homebrew/Library/Homebrew/utils.rb:606:in `with_env'
	from /opt/homebrew/Library/Homebrew/formula.rb:2704:in `block in stage'
	from /opt/homebrew/Library/Homebrew/resource.rb:158:in `block (2 levels) in unpack'
	from /opt/homebrew/Library/Homebrew/download_strategy.rb:116:in `chdir'
	from /opt/homebrew/Library/Homebrew/download_strategy.rb:116:in `chdir'
	from /opt/homebrew/Library/Homebrew/download_strategy.rb:103:in `stage'
	from /opt/homebrew/Library/Homebrew/resource.rb:154:in `block in unpack'
	from /opt/homebrew/Library/Homebrew/mktemp.rb:77:in `block in run'
	from /opt/homebrew/Library/Homebrew/mktemp.rb:77:in `chdir'
	from /opt/homebrew/Library/Homebrew/mktemp.rb:77:in `run'
	from /opt/homebrew/Library/Homebrew/resource.rb:266:in `stage_resource'
	from /opt/homebrew/Library/Homebrew/resource.rb:153:in `unpack'
	from /opt/homebrew/Library/Homebrew/resource.rb:127:in `stage'
	from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/forwardable.rb:230:in `stage'
	from /opt/homebrew/Library/Homebrew/formula.rb:2684:in `stage'
	from /opt/homebrew/Library/Homebrew/formula.rb:1318:in `brew'
	from /opt/homebrew/Library/Homebrew/build.rb:133:in `block in install'
	from /opt/homebrew/Library/Homebrew/utils.rb:606:in `with_env'
	from /opt/homebrew/Library/Homebrew/build.rb:128:in `install'
	from /opt/homebrew/Library/Homebrew/build.rb:229:in `<main>'

Desktop (please complete the following information):

  • OS: macOS Ventura 13.2.1
  • Browser n/a
  • Version n/a

Additional context
Add any other context about the problem here.

Subscriptions listen-method not available

Trying to make a subscription I discovered, that listen is not a method available after import SwiftGraphQL. Instead it tries to use a listen function with the following signature: listen(Int32, Int32) -> Int32

Maybe it is just about declaring it public?

A reproduction should be simple. Sadly there was also no example in the examples directory. If I am doing something wrong maybe it would be nice to see an example there. The one from the documentation simply does not work for me.

Maping a scalar to float results in 'AnyCodable does not conform to Decoder'

Describe the bug

I have a scalar mapping to Float for my generated code targeting BrainTrees api.

This doesn't seem to effect Int

The generated code results in
image

The Int version for example
image

To Reproduce
Steps to reproduce the behavior:

Create a graphql scalar of Amount, then map Scalar to Float in config. Then generate api using CLI

Expected behavior
A clear and concise description of what you expected to happen.

Generated code compiles without error

Screenshots
If applicable, add screenshots to help explain your problem.

  • Device: Macbook Pro 2015
  • OS: MacOS 12.6.2 (21G320)
  • Browser [e.g. stock browser, safari]
  • Version 4.0.2
    Additional context
    Add any other context about the problem here.

XCode Version 14.2 (14C18)

Multiple queries on the same socket

Right now we create a new websocket for each query which is quite performant heavy and not necessary.

You can send multiple queries on one socket. You then define the results that you get back per id.

We'll need to change the listen part quite a lot for this so I'm looking for some feedback on how we should do it.

We need a way to share a socket between listen calls

So either;

  1. Save a socket for each endpoint without the user seeing them in a static variable or something.
  2. Have the user handle the socket; so have a createWebsocket function that gives the user an opened socket that they can give to the listen function.

The listen call needs to return something that you can use to stop that single query that you started.

In the listen call I will add an id to the message (this was already commented). To stop a query from listening you need its id so we could;

  1. Just return the id and have a function to stop listening per id.
  2. Return an object that has a close function to stop listening to its query.

`make install` fails

Installing swift-graphql (either through homebrew or make install) currently fails to build:

/private/tmp/SwiftGraphQL-20220315-23016-185y7qo/swift-graphql-2.3.0/.build/checkouts/SwiftFormat/Sources/CommandLine.swift:556:44: error: 'temporaryDirectory' is only available in macOS 10.12 or newer
                return FileManager.default.temporaryDirectory

Linux support

Is your feature request related to a problem? Please describe.
It would be nice to have the library available on Linux too, e.g. to use the GraphQL client in server-sided applications.

Describe the solution you'd like
Add support for Linux by...

Concurrency related crash in SwiftGraphQLClient

Describe the bug
Crash due to concurrency issue of SwiftGraphQLClient Client in Core.swift function
public func execute(operation: Operation) -> Source
line 127: active[operation.id] = source
accessing (read/write) of active dictionary from concurrent threads

To Reproduce
Query from different threads simultaneously

Expected behavior
Client can handle concurrent threads accordingly.

Screenshots
none

  • iOS 16
  • Swift build tool version: 5.7
  • Xcode: 14.0.1

Additional context
none

Multiple variables with the same value in GraphQL request ends up failing

Describe the bug
If passing two identical strings as parameters to a mutation, the final POST body being sent seems to be optimized to a single variable, which produces an error in our GraphQL server.

I'm passing email and password as two identical parameters "asd".

Here's the query payload that's being sent to our server:

{
  "query”: “mutation ($__i6uv6ixjnetj: String!, $__i6uv6ixjnetj: String!)
  {
    createUser__bm9w5hv7q7ub: createUser(email: $__i6uv6ixjnetj, password: $__i6uv6ixjnetj)
    {
      __typename
      success___9371xkl2k0n: success
      error___9371xkl2k0n: error
      userId___9371xkl2k0n: userId
    }
  }“,
  “variables“:
  {
    “__i6uv6ixjnetj“:“asd“
  }
}

Response from server:

"{"errors":[{"message":"There can be only one variable named \"_1imzpym4atbyu\".","locations":[{"line":1,"column":12},{"line":1,"column":38}],"extensions":{"code":"GRAPHQL_VALIDATION_FAILED","exception":{"stacktrace":["GraphQLError: There can be only one variable named \"_1imzpym4atbyu\"."," at Object.VariableDefinition (/app/node_modules/graphql/validation/rules/UniqueVariableNames.js:31:29)"," at Object.enter (/app/node_modules/graphql/language/visitor.js:324:29)"," at Object.enter (/app/node_modules/graphql/language/visitor.js:375:25)"," at visit (/app/node_modules/graphql/language/visitor.js:242:26)"," at Object.validate (/app/node_modules/graphql/validation/validate.js:73:24)"," at validate (/app/node_modules/apollo-server-express/node_modules/apollo-server-core/dist/requestPipeline.js:221:34)"," at Object. (/app/node_modules/apollo-server-express/node_modules/apollo-server-core/dist/requestPipeline.js:118:42)"," at Generator.next ()"," at fulfilled (/app/node_modules/apollo-server-express/node_modules/apollo-server-core/dist/requestPipeline.js:5:58)"," at runMicrotasks ()"," at processTicksAndRejections (internal/process/task_queues.js:93:5)"]}}}]}\n"

Is this optimization intentional? Seems like our server does not like that.

If I am passing email and password as non-identical values then everything works correctly.

Thanks!

Prettify the generated code

Current code that the generator spits out is not properly formatted - indentation is misplaced, newlines are not optimally placed. We should format the code before we print it to a destination file.

Remove Type from SelectionSet class.

Remove Type from SelectionSet class as we don't use it anywhere and it pollutes code suggestions and the library itself.

It seems obvious when you think about it that SelectionSet should solely depend on the type it's representing and not the type user maps to in the selection.

Looking for Co-Maintainer 👋

Hi everyone 👋 ,

I am Matic (Matt), the creator of swift-graphql and I am looking for someone to help me work on the library.

I am looking for someone who is a seasoned Swift developer and would also be interested in promoting the project by speaking at the conferences. I'd help with the direction of the library, the code quality standard and programming, and you'd do everything that sounds fun to you.

I can only offer much besides public endorsement, gratefulness and loads of fun, (and possibly some swag 😎).

Let me know if you'd be interested and let's start collaborating! 😄

Add a way to access response headers

Is your feature request related to a problem? Please describe.
I want to access response headers because I need to save authorization tokens from server

Describe the solution you'd like
Would be nice if completionHandler of send function return the HTTPURLResponse which exposes the property allHeaderFields

Describe alternatives you've considered
I've wrote a custom URLProtocol to intercept the request and the response with custom logic to add my tokens on keychain

Error: unknownScalar("JSON")

Describe the bug
Running the code generator on a remote schema with "JSON" as scalar procudes error.

To Reproduce
Try to generate swift code from a schema that has JSON scalar fields.
For example:

{
  "name": "documents",
  "description": null,
  "args": [],
  "type": {
    "kind": "SCALAR",
    "name": "JSON",
    "ofType": null
  },
  "isDeprecated": false,
  "deprecationReason": null
},

Expected behavior
I am not sure what should happen.
Is this an illegal schema? If so, can you point to any official guideline/recommendation that I can send to our backend developers?

Error running codegen using commercetools GraphQL API

Describe the bug

When trying to run codegen against the commercetools GraphQL API endpoint, the process halts with error:

Cannot get unkeyed decoding container -- found null value instead.

This looks to be an error parsing / decoding the returned schema.

To Reproduce

$ swift-graphql "https://api.europe-west1.gcp.commercetools.com/insert-instance-name-here/graphql" --authorization "Bearer <auth token here>"

Doing this, we get errror:

Error: valueNotFound(
	Swift.UnkeyedDecodingContainer,
	Swift.DecodingError.Context(
		codingPath: 
			CodingKeys(stringValue: "data", intValue: nil),
			CodingKeys(stringValue: "__schema", intValue: nil)
			CodingKeys(stringValue: "types", intValue: nil),
			_JSONKey(stringValue: "Index 71", intValue: 71),
			CodingKeys(stringValue: "interfaces", intValue: nil)
		debugDescription: "Cannot get unkeyed decoding container -- found null value instead.", underlyingError: nil
	)
)

Expected behavior

Codegen runs without error

Missing GQL_CONNECTION_INIT message in Subscriptions

We did not send the GQL_CONNECTION_INIT message when creating a websocket which meant a server would not start sending keepalive messages. Not sure why the websocket doesn't time out in the example but it does for me in production.

I have a quick fix ready but the subscription part should be rebuilt to use only a single websocket for multiple queries to the same server.

Expose GraphQLAST and SwiftAST libraries

We should expose GraphQLAST part of the generator as a standalone package. Additionally, we should try to create an internal representation of Swift code (SwiftAST) that would let us programmatically define the code and take care of pretty-printing it into Swift code.

How do I display GraphQLError message?

Describe the bug
My GraphQL server has a case that returns an error, and in the app this is received as a GraphQLError I want to display the error message accompanying it.

Trying to access the message on GraphQLError just says:
'message' is inaccessible due to 'internal' protection level

Pointing to Result.swift, line 49

Expected behaviour
I would expect message to be accessible or printable either as public or via localisedDescription similar to system behaviour of Error, NSError types.


I don't quite understand but what is the use of message if only internal?

Let me know if I am missing something or there is a better approach.

Also happy to make a pull request making it public / helper function for accessing errors!

Allow arbitrary names for Query type.

Currently, we rename all operation names to default ones (i.e. Query, Mutation, Subscription). We should make it so that operation type keep their names in the generation step.

Error: unknownScalar("DateTime")

Describe the bug
Hi there, I've been trying to get the GraphQL schema from an endpoint but it the command-line client swift-graphql fails on that endpoint where Apollo Client works fine. I followed your explanation passing a .yml with the following content :

scalars:
  Date: DateTime
  Upload: Upload

.. but I still get the error.

To Reproduce
swift-graphql https://my_hostname/my_graphql_endpoint
OR
swift-graphql https://my_hostname/my_graphql_endpoint --config swiftgraphql.yml

Any clue ?

Cannot find type 'Fields' in scope

Describe the bug
Hi,

First of all, thanks for creating this awesome package.

I just added SwiftGraphQL to my project and successfully generated the API.swift code, however the app does not compile anymore. I'm getting a ton of "Cannot find type 'Fields' in scope" errors from that API.swift file.

To Reproduce
Steps to reproduce the behavior:
Add SwiftGraphQL 1.1.2 to your project, setup the codegen part and, add the API.swift to your project and build the app.

Thanks.

Package resolution error due to unstable version of swift-format

Describe the bug
Adding swift-graphql as a package dependency results in this error:

Failed to resolve dependencies. Dependencies could not be resolved because 'my-package' depends on 'swift-graphql' 4.0.4..<5.0.0.
'swift-graphql' >= 4.0.4 cannot be used because package 'swift-graphql' is required using a stable-version but 'swift-graphql' depends on an unstable-version package 'swift-format' and no versions of 'swift-graphql' match the requirement 4.0.5..<5.0.0.

To Reproduce
Steps to reproduce the behavior:

  1. Create a new Swift package.
  2. Add swift-graphql as a package dependency. .package(url: "https://github.com/maticzav/swift-graphql/", from: "4.0.4")
  3. Observe the error in package resolution.

Expected behavior
Adding a tagged release of swift-graphql should not result in package resolution errors.

Additional context
This appears to be due to swift-graphql depending on the main branch of swift-format rather than a tagged release.

number-prefixed words in multi-line descriptions trigger generator error

Describe the bug
A description containing words like "720p" throws:

Error: Unexpected token p at 403:23

upon generating Swift via swift-graphql.

To Reproduce
Add a documented type to a schema:

"""
Resolution
Example: Medium is 720p
"""
enum Resolution {
  LOW
  MEDIUM
  HIGH
}

Start GraphQL server, then confirm description integrity:

curl -X POST -H"Content-Type: application/json" -d '{"query":"query{__type(name:\"Resolution\") {name description}}"}' http://localhost:8080/query

Resulting in:

{"data":{"__type":{"name":"Resolution","description":"Resolution\nExample: Medium is 720p"}}}

Generate Swift:

swift-graphql http://localhost:8080/query

Expected behavior
Swift output.

Apostrophes in descriptions trigger generator error

Describe the bug
Descriptions containing apostrophes throws:

Error: Unexpected token 's at 123:39

upon generating Swift via swift-graphql

To Reproduce
Add a documented type to schema:

input AuthenticateInput {
  """User's registered email"""
  email: String!
  }

Confirm that the description is valid and then try to generate swift:
swift-graphql http://localhost:8000/query

Expected behavior
Swift output

Code Generation v4.0.0 sytax error

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to installation
  2. Run through the generator installation via Brew
  3. try to run swift-graphql --help or swift-graphql <url> for code generation
  4. See error

Expected behavior
Expected to see the help menu or to generate the code based on the url.

Screenshots
If applicable, add screenshots to help explain your problem.

dyld[11265]: Library not loaded: '@rpath/lib_InternalSwiftSyntaxParser.dylib'
  Referenced from: '/usr/local/Cellar/swiftgraphql/4.0.0/bin/swift-graphql'
  Reason: tried: '/usr/lib/swift/lib_InternalSwiftSyntaxParser.dylib' (no such file), '/usr/local/Cellar/swiftgraphql/4.0.0/bin/lib_InternalSwiftSyntaxParser.dylib' (no such file), '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.5/macosx/lib_InternalSwiftSyntaxParser.dylib' (no such file), '/usr/lib/swift/lib_InternalSwiftSyntaxParser.dylib' (no such file), '/usr/local/Cellar/swiftgraphql/4.0.0/bin/lib_InternalSwiftSyntaxParser.dylib' (no such file), '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.5/macosx/lib_InternalSwiftSyntaxParser.dylib' (no such file), '/usr/local/lib/lib_InternalSwiftSyntaxParser.dylib' (no such file), '/usr/lib/lib_InternalSwiftSyntaxParser.dylib' (no such file)
[1]    11265 abort      swift-graphql --help

Desktop (please complete the following information):

  • OS: macOS Monterey
  • Browser: n/a (in terminal)
  • Version 12.6

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.
Latest update seems (4.0.0) to have broken code generation

==> maticzav/swift-graphql/SwiftGraphQL: stable 4.0.0, HEAD
Code generator for SwiftGraphQL library
https://swift-graphql.org
/usr/local/Cellar/SwiftGraphQL/4.0.0 (5 files, 15.8MB)
  Built from source on 2022-09-14 at 17:52:24
From: https://github.com/maticzav/swift-graphql/blob/HEAD/Formula/SwiftGraphQL.rb
License: MIT
==> Requirements
Required: Xcode ✔
==> Options
--HEAD

Down grading the swift package to 3.0.1 in Xcode 14.0 allows the project to still build. But as you can see above the code generator version is at 4.0.0 and has the above issues. I no longer have any of the older installations available to switch back to see if they still work, but I was seeing a similar syntax issue before upgrading to the latest code gen

Dependency iOS/macOS dependency error on SwiftSyntax

Describe the bug
The latest version of SwiftGraphql seems to introduce a dependency compilation bug with the SwiftSyntax package. Both the main branch as well as version 4.0.0 cause the XCode compiler to throw the following error:

/Users/ijonas/Library/Developer/Xcode/DerivedData/Ojai2-fxyzrqzzubyxgybaukbsxawldlnn/SourcePackages/artifacts/swift-syntax/_InternalSwiftSyntaxParser.xcframework:1:1: While building for iOS Simulator, no library for this platform was found in '/Users/ijonas/Library/Developer/Xcode/DerivedData/Ojai2-fxyzrqzzubyxgybaukbsxawldlnn/SourcePackages/artifacts/swift-syntax/_InternalSwiftSyntaxParser.xcframework'.

To Reproduce
Steps to reproduce the behavior:

Launch XCode
Create a brand new "iOS App" project
Add the "https://github.com/maticzav/swift-graphql/" package (either main or 4.0.0)
Add all products except for "swift-graphql Executable"
Run the project (or run Build)

Expected behavior
Be able to add SwiftGraphql as a dependency on "iOS-only projects".

Desktop (please complete the following information):

MacOS 12.5.1
XCode 13.4.1

Smartphone (please complete the following information):

  • Deployment Target: iOS 15.5
  • Run on Simulator: iPod Touch 7th Gen

(These were just XCode project defaults)

Github Actions are not publishing new versions to Brew. (also SPM can't automatically resolve)

Installing via Brew:

Downloading https://github.com/maticzav/swift-graphql/archive/2.0.0.tar.gz

Seems that after 2.0.0 you are using Github Actions for releases after each merge.
This is great but it seems to break Brew.

I also had trouble using SPM, I add to provide exact version to resolve it the first time, else it did not found the standard version published in the package

Allow generation of schema from JSON file

Is your feature request related to a problem? Please describe.
The current generation tool relies on executing a query on the target API endpoint. This may cause authentication issues, rate limiting etc.

Describe the solution you'd like
I'd like to be able to generate a tool based on provided JSON data, such as GitHub's official GraphQL API schema: https://github.com/octokit/graphql-schema/blob/master/schema.json.

Describe alternatives you've considered
Switching library, using other tool for generating the code, host the schema to use existing functionality requiring the endpoint to be active.

Additional context

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.