首页 > 解决方案 > 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
});

标签: graphql

解决方案


推荐阅读