How to create field resolver

RedwoodJS automatically maps GraphQL queries resolvers to api/src/services . How do I create a field resolver for a given GraphQL type?

@gfpacheco - I just posted an answer, let me know if this helps.

@sam - Actually it doesn’t, my question is about field resolvers (fields inside a given type, not root queries/mutations).

@gfpacheco - I might not understand - could you post some example code explaining a little bit more about what you’re trying to do?

@gfpacheco - after reading your issue (#316), I think I might understand more about what you’re dealing with. Take a look at the new issue I submitted (#324) and let me know if that helps at all.

Adding this for now but also looping in @peterp

Here’s a snippet from a conversation we just had:

…They need to export a named constant of the same type, with the name of the field.
The type is here:
redwood/packages/api/src/makeMergedSchema/makeMergedSchema.test.js at 70c05e47ee152f6ac4cd70e9df6675052a9ccaef · redwoodjs/redwood · GitHub
And it resolves here:
redwood/packages/api/src/makeMergedSchema/makeMergedSchema.test.js at 70c05e47ee152f6ac4cd70e9df6675052a9ccaef · redwoodjs/redwood · GitHub

Helpful?

I answered on Stack Overflow, but I’ll duplicate the answer here.


It’s almost identical to the way you do it with graphql-tools.

You export an object with the same name as your type in your service:

// services/person.js
export const Person = {
    age: (_args, { root }) {
      return new Date().getFullYear() - root.birthDate.getFullYear();
    },
}

As an aside, you could also export a resolvers in the person.sdl.js file (But services take precendence):

// graphql/person.sdl.js

export const schema = gql`/* ... */`

export const resolvers = {
  Query: {},
  Mutation: {},
  Person: {},
}
3 Likes