graphql - GraphQL 变异结构
问题描述
我正在尝试在 Typescript 中创建一个 Node.js graphql 服务器。我正在使用 Express 和 express-graphql。当我想创建一个新用户时,我对如何构建我的突变有一些问题。
我的目标是能够使用这样的突变:
mutation {
user {
create(
data: {
name: "Foo Bar"
}
) {
id,
name
}
}
}
这是我的用户类型:
import {
GraphQLObjectType,
GraphQLNonNull,
GraphQLBoolean,
GraphQLString,
GraphQLInputObjectType
} from 'graphql';
export const UserType = new GraphQLObjectType({
name: 'User',
description: 'A user of the application',
fields: () => ({
id: {
type: new GraphQLNonNull(GraphQLString),
description: 'The id of the user',
},
name: {
type: new GraphQLNonNull(GraphQLString),
description: 'The name of the user',
}
})
});
export const UserInputType = new GraphQLInputObjectType({
name: 'UserInputType',
description: 'User payload definition',
fields: () => ({
name: { type: new GraphQLNonNull(GraphQLString) }
})
});
这是我在服务器上定义突变的尝试:
// ../user/user-mutations.ts
export const userMutations = {
user: {
type: new GraphQLObjectType({
name: 'CreateUser',
fields: {
create: {
type: UserType,
args: {
data: {
type: new GraphQLNonNull(UserInputType),
}
},
resolve: async (rootValue, { data }) => {
return Object.assign(data, {
id: '123'
});
}
}
}
})
}
};
我的错误/输出:
{
"errors": [
{
"message": "Cannot convert undefined or null to object",
"locations": [
{
"line": 36,
"column": 3
}
],
"path": [
"user"
]
}
],
"data": {
"user": null
}
}
问题 1:这种构建突变的方式不是最优的吗?我是否应该做类似的事情:
mutation {
createUser(
name: "Foo Bar"
) {
id,
name
}
}
问题 2:如果我的第一个结构很好,我如何在服务器上修复我的突变结构以创建我的用户并返回请求的值?
编辑:这是我的顶级架构:
import { userQueries } from '../user/user-queries';
export const queries = {
...userQueries
};
import { userMutations } from '../user/user-mutations';
export const mutations = {
...userMutations
};
const rootQuery = new GraphQLObjectType({
name: 'RootQuery',
fields: queries
});
const rootMutation = new GraphQLObjectType({
name: 'RootMutation',
fields: mutations
});
export const schema = new GraphQLSchema({
query: rootQuery,
mutation: rootMutation
});
解决方案
推荐阅读
- django - Django CMS - 无法重新排序子插件
- tensorflow - 创建空间变压器网络时无错误
- python - 在 Kaggle 上导入自己的 Python 模块
- linux - mkdir 函数的一半有效,但 cd 部分无效
- discord.py - 消息发送命令有问题
- ios - Apple 的 SwiftUI 教程:我被难住了
- python - 如何使用 SQL Alchemy 编写手动复杂的原始 SQL 查询?
- c# - AutoHotKey NumPut 和 VarSetCapacity 的 C# 等效项
- angular - 在将整个数据加载到 Angular 之前,如何显示 ngx-spinner
- copy - 将过滤后的行从一个 google 工作表批量复制到另一个 google 工作表