Search code examples
redwoodjs

How to create field resolver on RedwoodJS


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

Suppose I have this schema:

type Person {
  name: string!
  birthDate: DateTime!
  age: Int!
}

But only name and birthDate are stored in the database.

Using graphql-tools I would write my resolvers like this:

const resolvers = {
  Query: { ... },
  Mutation: { ... },
  Person: {
    age(person) {
      return new Date().getFullYear() - person.birthDate.getFullYear();
    },
  },
};

PS: I know the age formula is wrong.

PS2: I'm using age here for the sake of simplicity, imagine this is expensive to compute or get from database.


Solution

  • 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: {},
    }