How to design schema in GraphQL considering input types for mutation?

458 views Asked by At

Does this schema look correct?

type User {
    id : ID!
    username : String!
    email : String!
    name : String!
}

input UserInput {
    username : String!
    email : String!
    name : String!
}

mutation createNewUser($usr: UserInput!) {
  createUser(user: $usr)
}

As internal id for the user will be assigned upon user creation, Should there be separate type and input in this schema or User could be made input? So that schema looks like this

input User {
    id: ID
    username : String!
    email : String!
    name : String!
}

mutation createNewUser($usr: User!) {
  createUser(user: $usr) : User
}
2

There are 2 answers

0
Aᴍɪʀ On BEST ANSWER

You are right on the money in your first approach. The id field can not be null (id: ID!) and it can not have a value when you need to create the user, so you need to have another input type for it.

As mattdionis also pointed out, there's a very similiar sample in the docs.

0
Noyal On

Your schema should be

const typeDefinitions = `
type User {
    id : ID!
    username : String!
    email : String!
    name : String!
}

input UserInput {
    username : String!
    email : String!
    name : String!
}

type Mutation {
  createUser(user: UserInput) User
}

schema {
  mutation:Mutation
}
`;

export default [typeDefinitions];