ferry icon indicating copy to clipboard operation
ferry copied to clipboard

Fragments not working with interfaces

Open letsar opened this issue 5 months ago • 5 comments

When I create a Fragment with a type which is an interface, or has fields which are interfaces, the generated code does not work at runtime.

For example let's have this schema:

interface Book {
  title: String!
  author: String!
}

type Textbook implements Book {
  title: String!
  author: String!
  courses: [String!]!
}

type ColoringBook implements Book {
  title: String!
  author: String!
  colors: [String!]!
}

type Query {
  books: [Book!]!
}

And this query:

fragment BookFragment on Book {
  title
  ... on Textbook {
      courses
  }
  ... on ColoringBook {
      colors
  }
}

query GetBooks {
  books {
    ...BookFragment
  }
}

These parameters are set on build.yaml:

  when_extensions:
    when: true
    maybeWhen: true

When we generate the code, we can see that nothing implements GBookFragment__asTextbook, yet we have this kind of generted code:

extension GBookFragmentWhenExtension on GBookFragment {
  _T when<_T>({
    required _T Function(GBookFragment__asTextbook) textbook,
    required _T Function(GBookFragment__asColoringBook) coloringBook,
    required _T Function() orElse,
  }) {
    switch (G__typename) {
      case 'Textbook':
        return textbook((this as GBookFragment__asTextbook));
      case 'ColoringBook':
        return coloringBook((this as GBookFragment__asColoringBook));
      default:
        return orElse();
    }
  }
}

Since nothing implements GBookFragment__asTextbook, the cast (this as GBookFragment__asTextbook) will fail. Is there a workaround for that?

letsar avatar Sep 02 '24 09:09 letsar