GraphQL突变结构

时间:2018-05-04 16:15:38

标签: 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
});

0 个答案:

没有答案