AddMutation using relay modern graphql

2019-08-26 16:48发布

问题:

I'm trying to add a user using relay , below is my schema file
schema.graphql

createUser(input: CreateUserInput!): UserPayload

input CreateUserInput {
clientMutationId: String
data: CreateUserData!
}

type CreateUserData {
firstName: String!
lastName: String!
password: String!
email: String
}

type UserPayload {
clientMutationId: String
node: User
}

type User {
id: ID!
firstName: String!
lastName: String!
email: String
password: String
}

below is my mutation file ,
AddUserMutation.js

const mutation = graphql`
  mutation AddUserMutation($input:  CreateUserInput!) {
  createUser(input: $input) {
      data {
        firstName
        lastName
        email
        password
      }
    }
  }
`;

function commit(environment, node) {
  var firstName = node.fName;
  var lastName = node.lName;
  var email = node.signupEmail;
  var password = node.pwd;
  return commitMutation(environment, {
    mutation,
    variables: {
    input: {
       firstName,
       lastName,
       email,
       password
    },
  },onCompleted: (response, errors) => {
        console.log('Response received from server.',response)
      },
      onError: err => console.error(err),
    },
  );
}

export default { commit };

But it is throwing me this error

GraphQLParser: Unknown field data on type UserPayload. Source: document AddUserMutation file: js/mutations/AddUserMutation.js.

so what i did wrong here , i searched many sites still able to find a solution for this . can someone help/clarify me on this .

回答1:

According to your schema, the createUser mutation resolves to an object of the UserPayload type. That type has only two fields in your schema:

type UserPayload {
  clientMutationId: String
  node: User
}

However, your query is actually requesting a data field, which doesn't exist for the UserPayload type. You'll need to modify your query to request the correct fields, for example:

const mutation = graphql`
  mutation AddUserMutation($input:  CreateUserInput!) {
  createUser(input: $input) {
      node: {
        firstName
        lastName
        email
        password
      }
    }
  }
`;

You may also need to change your schema, since CreateUserData should be an input not a type.