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 config to to default to null for nullable relationships #128

Closed gurschitz closed 1 year ago

gurschitz commented 1 year ago

This is kind of related to this issue. As mentioned there, we rarely want to have default for relationships to generate example data.

We were thinking that it would be very nice to have a config that would always generate null instead of using a generator functions for fields that are nullable.

e.g. back to the example:

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

type Series {
  id: ID!
}

With a config - for example defaultNullableToNull for the lack of a better name - the above would generate this:

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! : null
    };
};

This would make it more maintainable for us, since we would not need to specify the overrides via fieldGeneration for each field that we want to be null.

Somewhat related to that, it would be also helpful if listElementCount would allow 0 as a value, which would allow us to have the same effect for lists. Currently, this is not possible due to this line.

Does that make sense? If so, I could have a go at this.

ardeois commented 1 year ago

Thanks for the suggestions @gurschitz it makes sense.

Feel free to open a PR to add defaultNullableToNull option (didn't find a better name either 🙂 )

As for listElementCount, I also agree, we should instead check if config.listElementCount is defined. Something like config.listElementCount ?? 1 or 'listElementCount' in config ? config.listElementCount : 1