Skip to content

Fragments not working with interfaces #610

@letsar

Description

@letsar

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?

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions