reactjstypescriptgraphqlgraphql-codegen

get sub types in graphql query using @graphql-codegen/cli


I have a below query

export const GET_ALL_ADVERT_CUSTOM_FIELD = gql(`
  query advertCustomFields {
    advertCustomFields {
      nodes {
        slug
        valueType
        displayName
        description
        canRead
      }
    }
  }
`)

And I would like to get the list filtered of nodes like this

import { Props as SelectProps } from 'react-select'
import React, { FC, useState } from 'react'
import ObjectSelector from 'components/Common/ObjectSelector'
import OptionWithDescription from './OptionWithDescription'
import { useQuery } from '@apollo/client'
import { AdvertCustomFieldsDocument } from '__generated__/graphql'

export const AdvertCustomFieldSelector: FC<SelectProps> = (props) => {
  const [data, setData] = useState<NodeType[]>()
  useQuery(AdvertCustomFieldsDocument, {
    onCompleted: (res) => {
      const filterData = res.advertCustomFields?.nodes?.filter((e) => e.canRead)
      setData(filterData)
    },
  })

  return (
    <ObjectSelector<Node>
      name={props.name}
      onChange={props.onChange}
      options={data as any}
      getOptionLabel={(option) => option?.displayName as string}
      getOptionValue={(option) => `${option.slug}`}
      components={{ Option: OptionWithDescription }}
    />
  )
}

The thing is @graphql-codegen/cli does not export type for the NodeType.

This is my codegen config

import { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
  schema: './app/graphql/schema.graphql',
  documents: ['./facerberus/components/**/*.ts'],
  ignoreNoDocuments: true, // for better experience with the watcher
  generates: {
    './facerberus/__generated__/': {
      preset: 'client',
      plugins: [],
      presetConfig: {
        gqlTagName: 'gql',
      },
    },
  },
}

export default config

which config to make codegen export type of NodeType or how to achieve it via ts


Solution

  • Codegen doesn't generate a standalone type for every part of the operaation. But you can easily extract the needed part from the operation type. Should be something like this: type NodeType = AdvertCustomFieldsQuery['advertCustomFields']['nodes'][number]