Структура мутации GraphQL - PullRequest
0 голосов
/ 04 мая 2018

Я пытаюсь создать сервер Node.js graphql в Typescript. Я использую 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
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...