Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Request: Field Resolver Example for Nested Types #54

Open
danstarns opened this issue Jan 25, 2025 · 0 comments
Open

Request: Field Resolver Example for Nested Types #54

danstarns opened this issue Jan 25, 2025 · 0 comments

Comments

@danstarns
Copy link

Hi team,

I wanted to make an issue here to request an example using nested field resolvers. One of the benefits of GraphQL is that only what you call is resolved.

Say we have a posts query that also has comments. We don't want to fetch the comments unless they are specifically requested in the GraphQL query. This would make a great example using the JSONPlaceholder API.

I found an example of nested types in the dgraph-101 project:

export function getProduct(id: string): Product | null {

However, this always fetches the category data even if it's not requested in the GraphQL query. I'm not sure if nested resolvers are currently supported, but it would be valuable to demonstrate this pattern.

Proposed Implementation using JSONPlaceholder:

import { http } from "@hypermode/modus-sdk-as"

@json
export class Comment {
  postId!: number
  id!: number 
  name!: string
  email!: string
  body!: string
}

@json
export class Post {
  id!: number
  userId!: number
  title!: string
  body!: string
  comments: Comment[] = []
}


/**
 * Get a list of posts. Comments will only be fetched when the comments field is requested.
 */
export function getPosts(): Post[] {
  const request = new http.Request("https://jsonplaceholder.typicode.com/posts")
  const response = http.fetch(request)
  return response.json<Post[]>()
}

/**
 * Field resolver for Post.comments - only called when comments are requested
 */
export function resolvePostComments(post: Post): Comment[] {
  const request = new http.Request(
    `https://jsonplaceholder.typicode.com/posts/${post.id}/comments`
  )
  const response = http.fetch(request)
  return response.json<Comment[]>()
}

This would allow queries like:

# Just posts - comments not fetched
query {
  posts {
    id
    title
  }
}

# Posts with comments - comments fetched via resolver
query {
  posts {
    id
    title
    comments {
      id 
      body
    }
  }
}

Can someone confirm if field resolvers are supported? If so, this would make a great example here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant