apollographql / apollo-tooling

✏️ Apollo CLI for client tooling (Mostly replaced by Rover)
https://apollographql.com
MIT License
3.04k stars 468 forks source link

Support automatic Identifiable protocol generation in Swift Codegen #1809

Open ericlewis opened 4 years ago

ericlewis commented 4 years ago

It would be awesome if the swift codegen had an option to detect and automatically generate the correct protocols to conform to Identifiable when a GraphQLSelectionSet has an id property.

It is currently possible to write code to conform, but it is fragile:

// assumes that PeopleQuery.Data.AllPerson.Edge.Node has an id property as specified by .graphql
extension PeopleQuery.Data.AllPerson.Edge.Node: Identifiable {
}

Proposed Solution

The proposed solution would be to add an optional flag and generate the extensions in the current codegen, but it may perhaps be easier to traverse the AST of the generated API as a separate step. Advice is welcome if folks have done this before.

Reasoning

While it is currently possible to support this solution today- it is tedious to rewrite the same code.

extension PeopleQuery.Data {
    var flattenedEdges: [Self.AllPerson.Edge.Node] {
        allPeople?.edges?.compactMap { $0?.node } ?? []
    }
}

extension PeopleQuery.Data.AllPerson.Edge.Node: Identifiable {
}

extension PlanetsQuery.Data {
    var flattenedEdges: [Self.AllPlanet.Edge.Node] {
        allPlanets?.edges?.compactMap { $0?.node } ?? []
    }
}

extension PlanetsQuery.Data.AllPlanet.Edge.Node: Identifiable {
}
designatednerd commented 4 years ago

This is 100% in the plan for the shift to swift based codegen: https://github.com/apollographql/apollo-ios/issues/939

ericlewis commented 4 years ago

@designatednerd fantastic! I built a semi-hacky way to handle identifiable generation: https://github.com/ericlewis/StarWarz/blob/master/StarWars/process.js

usage: sourcekitten structure --file API.swift > output.json && node process.js

ericlewis commented 4 years ago

Also of interest is how I integrate Apollo with SwiftUI perhaps too! 👍

Dreamystify commented 3 years ago

Where do you add these extensions? in which file and where, new to ios and apollo and swiftui here...