graphqlgraphql-jsgraphql-tools

How to nest qraphql resolvers so as to group them


I'm wrapping a series of REST APIs in GraphQL and I'm having trouble getting a resolver to work.

My typeDefs

const typeDefs = `
  type Page {
    id: String
    path: String!
    title: String!
    heading: String
    type: String
    html: String
    summary: String
  }

  type Site {
    page(path: String!): Page
  }

  type Query {
    site: Site
  }`

and my resolvers

const resolvers = {
  Query: {
    site: {
      page: async (_root, { path }) => getPage(path)
    }
  }
}

If I try this query

{
  site {
    page(path: "/services/research-request") {
      id
      path
      title
      html
      type
      summary
    }
  }
}

I get back

{
  "data": {
    "site": null
  }
}

However if I don't nest the page within the site

const typeDefs = `
  type Page {
    id: String
    path: String!
    title: String!
    heading: String
    type: String
    html: String
    summary: String
  }

  type Query {
    page(path: String!): Page
  }`

and use resolvers

const resolvers = {
  Query: {
    page: async (_root, { path }) => getPage(path)
  }
}

then I try this query

{
  page(path: "/services/research-request") {
    id
    path
    title
    html
    type
    summary
  }
}

I get back, correctly,

{
  "data": {
    "page": {
      "id": "d290f1ee-6c54-4b01-90e6-d701748f0851",
      "path": "/services/research-request",
      "title": "Research | Requests",
      "html": "<p>This is a really well put together Research Requests page<p>\n",
      "type": "page",
      "summary": "A short piece of summary text"
    }
  }
}

I'm going to be pulling in data from a number of APIs to populate my graph so wanted to group the various parts according to site vs user, etc but I'm missing something obvious when trying to nest the resolvers. What am I doing wrong?


Solution

  • No 'free' nesting in graphql ... nest > next level depth > next TYPE ... site resolver, site.page resolver ... but also own site id (for client cache), rebuild/adjust all clients code etc. ...

    Namespacing should be better: sitePage, siteOptions, userProfile, userSettings ... use alias (or replace in files) for renaming in client.