Apollo-ios: Switch with associated data instead of constructor methods for partials

Created on 15 Jun 2020  路  4Comments  路  Source: apollographql/apollo-ios

This is a feature request.

Current implementation

Given a Node interface type and A, B, and C types that conform to it, it the following schema:

interface Node {
    id: ID!
}

type A implements Node {
    id: ID!
    name: String
}

# ... etc

type Query {
    node: Node
}

the code generator for the following query

query NodeQuery {
    node {
        id
        ... on A {
             name
        }
    }
}

would generate code that has asA getter producing an optional of A swift type.

This means for N types, we have to write N if let valueA = data.node.asA clauses.

Proposal

Generate an enum for Node type that has all of the type's known implementors as cases.

enum Node {
    case A(data: StructA)
    case B(data: StructB)
    // etc...
}

which would allow for a simpler access of the interface values using a switch, while still allowing if ... else syntax using if case let.

codegen enhancement

All 4 comments

It's a little hard to do it with the associated types since each type is different per query to make sure you're only trying to use the specific type requested in that query. However, I am working on something similar in this PR for the Swift Codegen project that will at least let you switch on the __typename.

You're right. I have overlooked the query-tie-in! in context of a query, the interface types remain a switch-able condition. It's just that Node type wouldn't be global:

struct NodeQuery {
    enum Node {
        case A(data: NodeQuery.StructA)
    }
}

and its cases would follow the same definition logic currently used for the asType getters.

__typename addition sounds like fun and I can't wait to use it!

I do see how the Node type appearing in different branches of the query would produce a different struct type in the associated value signature. Took me a second to get there. You're right.

馃 I'm gonna do some noodling on this and see what might be doable - I like where you're going with it though.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

maxsz picture maxsz  路  4Comments

sfla picture sfla  路  3Comments

Dmurph24 picture Dmurph24  路  4Comments

Robuske picture Robuske  路  3Comments

dchohfi picture dchohfi  路  4Comments