ardeois / graphql-codegen-typescript-mock-data

[GraphQL Codegen Plugin](https://github.com/dotansimha/graphql-code-generator) for building mock data based on the schema.
MIT License
132 stars 47 forks source link

allow `null` as default value for relationships #119

Closed gurschitz closed 1 year ago

gurschitz commented 1 year ago

Hey there, first of all, thanks for the great plugin, it's really a big help for us. 🙏

In our GraphQL Schema, we have nested relationships that are nullable. A simple example:

type Post {
  id: ID!
  series: Series
  publishedAt: String
}

type Series {
  id: ID!
}

A Post can have a Series, but for us it is rather the exception than the rule that this is the case.

The config for the plugin looks like this:

typescript-mock-data:
  typesFile: './graphqlTypes.ts'
  terminateCircularRelationships: true
  addTypename: true
  fieldGeneration:
    Post:
      publishedAt: 'null'

Right now, our generated output is something like this (simplified):

export const aPost = (overrides?: Partial<Post>, _relationshipsToOmit: Set<string> = new Set()): { __typename: 'Post' } & Post => {
    const relationshipsToOmit: Set<string> = new Set(_relationshipsToOmit);
    relationshipsToOmit.add('Post');
    return {
        __typename: 'Post',
        id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
        publishedAt: overrides && overrides.hasOwnProperty('publishedAt') ? overrides.publishedAt! : null,
        series: overrides && overrides.hasOwnProperty('series') ? overrides.series! : relationshipsToOmit.has('Series') ? {} as Series : aSeries({}, relationshipsToOmit)
    };
};

As you can see, for publishedAt it works fine to set the default value to null via the config. It would be great if there is a way to set the default value of series to null, so that we don't have to do the following all the time:

aPost({
  series: null
})

I have tried setting series to null to 'null' in the fieldGeneration config, but it didn't work. Also, I didn't find anything in the docs or in other issues about this unfortunately.

Maybe I miss something and it's already possible, but if not, do you think this could be added one way or the other? I am happy to do the implementation as well.

ardeois commented 1 year ago

This seems like a bug indeed, thanks for reporting it. Would you be down to create a PR to fix it? If you do, make sure to add unit test for this use case Thanks !

gurschitz commented 1 year ago

@ardeois great, thanks! Yes, I created a PR for this to fix it.