contentful

How to make contentful graphQL schemas treat "required" fields as required, not optional?


I have Contentful content models, and I fetch the GraphQL Schema that Contentful generates, and use it to generate Typescript types.

In my content model, some fields are set as "required" and some are left as "optional". My expectation is that this should be reflected in the GraphQL schema (and therefore also in the generated typescript types), but it's not. There's nothing in the graphQL schema to distinguish required and optional, so they all come through to Typescript as maybe undefined.

For example, a model has a "required" title and an "optional" description:

    {
      "id": "title",
      "name": "Title",
      "type": "Symbol",
      "localized": false,
      "required": true,
      "validations": [
        {
          "size": {
            "max": 150
          }
        }
      ],
      "disabled": false,
      "omitted": false
    },
    {
      "id": "description",
      "name": "Description",
      "type": "RichText",
      "localized": false,
      "required": false,
      "validations": [],
      "disabled": false,
      "omitted": false
    },

...but the corresponding GraphQL schema treats both as optional:

  description(locale: String): ReferenceToRichTextModelDescription
  ...
  title(locale: String): String

...so the generated typescript expects undefined for both cases:

  description?: Maybe<ReferenceToRichTextModelDescription>;
  ...
  title?: Maybe<Scalars['String']['output']>;

I want the required fields to be required in the schema (or at least, differentiated in some way so that I can make them required in my codegen step), but there seems to be no differentiation.

I've looked through Contentful's docs on graphQL schemas and content models, but can't find anything about this specific behaviour.


Solution

  • I couldn't find any documentation but I did eventually find a support forum question about this](https://support.contentful.com/hc/en-us/articles/18465058199453-Required-fields-on-GraphQL-schema). Unfortunately the behaviour appears to be by design, with no suggested workaround:

    The reason why all fields (even those that are required) are not marked as required is that the preview content is served through the same schema, and in preview mode, there are no validations (a required field might be empty) and so unfortunately this is by design since preview and published content are using the same schemas.

    "Required" and "Optional" fields are not differentiated in the Preview API, so they're not differentiated in the GraphQL schema, and there appears to be no current way to get a "Publish API flavour" version of the schema.

    It might be possible to extract the JSON field definition as the basis of typescript type codegen instead of the GraphQL schema, but it's not currently possible using the GraphQL schema.