如何在 Apollo GraphQL Server 中添加字段解析器
How to add field resolver in Apollo GraphQL Server
如何在 graphQL apollo 语法中添加字段解析器?使用 graphql 语法,如果我有一个有问题的讲座,我可以这样做:
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;
};
问题是我在每个解析器的基础上而不是在模式级别手动填充问题。这意味着我的查询只会填充我指定的固定深度,而不是基于请求的实际查询 return 参数。 (我知道这里没有 1:1 基础,因为我从 mongo 切换到发电机,但看起来这个解析器部分应该是独立的。)
如果以编程方式定义的 resolve
函数按预期工作,您可以在解析器对象中使用它 "as is":
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
}
如何在 graphQL apollo 语法中添加字段解析器?使用 graphql 语法,如果我有一个有问题的讲座,我可以这样做:
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;
};
问题是我在每个解析器的基础上而不是在模式级别手动填充问题。这意味着我的查询只会填充我指定的固定深度,而不是基于请求的实际查询 return 参数。 (我知道这里没有 1:1 基础,因为我从 mongo 切换到发电机,但看起来这个解析器部分应该是独立的。)
如果以编程方式定义的 resolve
函数按预期工作,您可以在解析器对象中使用它 "as is":
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
}