1
votes

How can I add field resolvers in the graphQL apollo syntax? Using the graphql syntax, if I had a lecture which had questions I can do this:

const LectureType = new GraphQLObjectType({
  name: 'LectureType',
  fields: () => ({
    id: { type: GraphQLID },
    questions: {
      type: new GraphQLList(QuestionType),
      resolve: ({ _id }, args, { models }) => models.Lecture.findQuestions(_id),
    },
  }),
});

What is the equivalent syntax using apollo graphQL? I'd think that I can do this type definition with this resolver:

  type QuestionType {
    id: String,
  }

  type LectureType {
    id: String,
    questions: [QuestionType],
  }

const getOne = async ({ args, context }) => {
  const { lecture, question } = constructIds(args.id);
  const oneLecture = await model.get({ type: process.env.lecture, id: lecture });
  oneLecture.questions = await model
  .query('type')
  .eq(process.env.question)
  .where('id')
  .beginsWith(lecture)
  .exec();
  return oneLecture;
};

The problem is that I'm populating the questions manually on a per resolver basis instead of at the schema level. This means that my queries will only get populated the fixed depth that I specify instead of based on the actually query return parameters requested. (I know there isn't a 1:1 basis here since I switch from mongo to dynamo, but it seems like this resolver part should be independent.)

1

1 Answers

7
votes

If the programmatically defined resolve functions works as intended, you can use it "as is" inside your resolvers object:

const typeDefs = `
type QuestionType {
  id: String,
}

type LectureType {
  id: String,
  questions: [QuestionType],
}
# And the rest of your schema...`

const resolvers = {
  LectureType: {
    questions: ({ _id }, args, { models }) => { 
      return models.Lecture.findQuestions(_id)
    }
  },
  Query: {
    // your queries...
  }
  // Mutations or other types you need field resolvers for
}