如何在Apollo GraphQL服务器中添加字段解析器
如何在graphQL apollo语法中添加字段解析器?使用graphql语法,如果我有一个有问题的讲座,我可以这样做:如何在Apollo GraphQL服务器中添加字段解析器,graphql,apollo,apollo-server,Graphql,Apollo,Apollo Server,如何在graphQL apollo语法中添加字段解析器?使用graphql语法,如果我有一个有问题的讲座,我可以这样做: const LectureType = new GraphQLObjectType({ name: 'LectureType', fields: () => ({ id: { type: GraphQLID }, questions: { type: new GraphQLList(QuestionType), resol
const LectureType = new GraphQLObjectType({
name: 'LectureType',
fields: () => ({
id: { type: GraphQLID },
questions: {
type: new GraphQLList(QuestionType),
resolve: ({ _id }, args, { models }) => models.Lecture.findQuestions(_id),
},
}),
});
使用apollo graphQL的等效语法是什么?我想我可以用这个解析器来定义这个类型:
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;
};
问题是,我在每个解析器的基础上手动填充问题,而不是在模式级别。这意味着我的查询将只填充我指定的固定深度,而不是基于实际请求的查询返回参数。(我知道这里没有1:1的基础,因为我从mongo切换到dynamo,但似乎这个解析器部分应该是独立的。)如果编程定义的
resolve
函数按预期工作,您可以在解析器对象内“按原样”使用它:
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
}
如果编程定义的
resolve
函数按预期工作,则可以在解析器对象中“按原样”使用它:
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
}
这非常有帮助,谢谢!我还有两个问题,我注意到在讲师类别中,您只解析问题,而不解析id。如果我想解析讲师类别中的id和其他属性,我是在讲师类别解析程序中还是在查询中进行解析?另外,我能为[讲师类型](即数组)提供一个单独的解析器吗?没关系,我想现在明白了。我在查询中进行讲座查找,然后由于返回类型是讲师类型,因此问题将在讲师类型解析程序中填写。再次感谢!这非常有帮助,谢谢!我还有两个问题,我注意到在讲师类别中,您只解析问题,而不解析id。如果我想解析讲师类别中的id和其他属性,我是在讲师类别解析程序中还是在查询中进行解析?另外,我能为[讲师类型](即数组)提供一个单独的解析器吗?没关系,我想现在明白了。我在查询中进行讲座查找,然后由于返回类型是讲师类型,因此问题将在讲师类型解析程序中填写。再次感谢!