【发布时间】:2017-02-22 17:35:11
【问题描述】:
我一直在编写一个使用 GraphQL 的 API。我对它还是很陌生,并且遇到了一些关于突变的问题。我的 API 的简单形式有两种记录类型。有联系人记录和标签记录。一个联系人记录可以关联多个标签记录。
我为每种记录类型编写的架构如下:
const Tag = new graphQL.GraphQLObjectType({
name: 'Tag',
description: 'Categorizes records into meaningful groups',
fields: () => ({
_id: {
type: graphQL.GraphQLID
},
name: {
type: graphQL.GraphQLString
}
})
});
const Contact = new graphQL.GraphQLObjectType({
name: 'Contact',
description: 'Contact record',
fields: () => ({
_id: {
type: graphQL.GraphQLID
},
name: {
type: graphQL.GraphQLString
},
tags: {
type: new graphQL.GraphQLList(Tag),
resolve: function(src, args, context) {
return TagModel.findByContactId(src._id)
.then(tags => {
return Promise.map(tags, (tag) => {
return TagModel.findById(tag.tag_id);
});
});
}
}
})
});
我可以对标签等记录进行足够简单的突变,因为它们不包含自己的嵌套记录,但我不确定如何对联系人等记录进行突变,因为它也可以包含标签.我放置的变异代码如下所示:
const Mutation = new graphQL.GraphQLObjectType({
name: 'Mutation',
fields: {
createContact: {
type: Contact,
description: "Create Contact",
args: {
name: {type: new graphQL.GraphQLNonNull(graphQL.GraphQLString)},
tags: {type: new graphQL.GraphQLList(Tag)}
},
resolve: function(source, args) {
return ContactModel.save(args.name);
}
}
}
});
我不确定如何在突变中完成解析器,以便能够同时保存联系人和标签记录。例如,如果我做了一个突变查询来保存一个带有新标签的新联系人记录,如下所示:
{"query": "mutation createNewContact {
contact: createContact (name: "John Smith", tags { name: "family" } )
{_id, text, tags { name } } }" }
为了让这种类型的突变发生,我需要在我的突变模式中做些什么特别的事情吗?
【问题讨论】:
标签: javascript api graphql