graphql-code-generator icon indicating copy to clipboard operation
graphql-code-generator copied to clipboard

suggestion for handling resolved types

Open jaminhaber opened this issue 7 months ago • 1 comments

Generating accurate types for resolved fields is still an unsolved problem, even if it is known which fields are resolved vs not. (Similar to the issue raised here: https://github.com/dotansimha/graphql-code-generator/issues/1780)

when using GQL code generator to generate resolver types for an api from a schema file, resolved fields are still declared on parent objects and must be stubbed or otherwise overridden.

example:

type Article {
  id: ID!
  authorId: ID!
  author: Author! # resolved
  title: String
}

would require something like this:

const article = {
  id: "article_id",
  author: "author_id",
  author: { id: "author_id" } as Author,
  title: "title"
}
// OR
const article = {
  id: "article_id",
  author: "author_id",
  title: "title"
} as Article

Describe the solution you'd like

Is it possible to make a config that can override fields based on directives?

type Author {
  id: ID!
  name: String!
}

type Article {
  id: ID!
  authorId: ID!
  author: Author! @resolved
  title: String
}

type Query {
  randomArticle: Article
}

scenario 1

An explicit config field for this behavior for this use case

config: {
   resolvedFieldDirective: "resolved"
}
type resolvers = {
  Article: {
    author: (Omit<Article, "author">) => Author
  },
  Query: {
    randomArticle  () =>  Omit<Article, "author">
  }
}

scenario 2

A generic config to modify types based on directives

config: {
   directiveTypeGeneration: {
     resolved: "undefined"
  }
}

Would result in something like this


type Article = {  ... } // all fields
 
type BaseArticle = Article & {
   author: undefined
}

type resolvers = {
  Article: {
    author: (BaseArticle) => Author
  },
  Query: {
    randomArticle  () =>  BaseArticle
  }
}

jaminhaber avatar Jul 11 '24 01:07 jaminhaber