heftapp / graphql_codegen

MIT License
145 stars 53 forks source link

Is __typename in idFields required when writing and reading fragments? #350

Open kvenn opened 6 months ago

kvenn commented 6 months ago

I see the docs mention the use of write and read like so:

  client.writeFragment$PersonSummary(
    idFields: {'__typename': 'Person', 'id': '1'},
    data: person.copyWith(name: 'Kurt'),
  );

But from this change, the Fragment already knows its own typename : https://github.com/heftapp/graphql_codegen/pull/247

Is it possible to generate a shorthand so I can just call it like so:

  client.writeFragment$PersonSummary(
    idFields: { 'id': '1'},
    data: person.copyWith(name: 'Kurt'),
  );

Or even better yet (since all of our idFields are the same for all our fragments):

  client.writeFragment$PersonSummary(
    id: '1'
    data: person.copyWith(name: 'Kurt'),
  );
github-actions[bot] commented 6 months ago

👋 @kvenn Thank you for raising an issue. I will investigate the issue and get back to you as soon as possible. Please make sure you have provided enough context.

This library is created and maintained by me, @budde377. Please consider supporting my work and ensure our survival by donating here.

budde377 commented 4 months ago

Good idea, thanks for raising it. I will investigate and see if its possible :)

kvenn commented 4 months ago

Incredible thank you!!

We've been using wrappers in our code which kind of exemplify our ideal API. The read (in our case) could only need a string ID and the write only needs the object (since it will have the ID on it). I know this makes the function a little less flexible, but maybe it's a building block on top of the default?

  Fragment$User? readUser(String id)
  void writeUser(Fragment$User user) 

Implementation

extension UserCache on GraphQLClient {
  Fragment$User? readUser(String id) =>
      readFragment$User(
        idFields: {
          '__typename': 'User',
          'id': id,
        },
      );

  void writeUser(Fragment$User user) =>
      writeFragment$User(
        idFields: {
          '__typename': 'User',
          'id': user.id,
        },
        data: user,
      );
}