Can you make a GraphQL type both an input and output type?

Yes, in GraphQL, you can define a type that serves both as an input and an output type. This is useful when you want to reuse the same structure for data input in mutations and data output in queries or mutations.

To create a type that can be used as both an input and an output type, you define the type in the schema using the “type” keyword, and then you can use that type in both input and output contexts.

Here’s an example of how you can define a type as both an input and output type in GraphQL:

type Person {
  id: ID!
  name: String!
  age: Int!
  email: String!
}

type Query {
  getPerson(id: ID!): Person
  getAllPeople: [Person!]!
}

type Mutation {
  createPerson(input: PersonInput!): Person
}

input PersonInput {
  name: String!
  age: Int!
  email: String!
}

In this example, we define a “Person” type with fields for “id,” “name,” “age,” and “email.” The “Person” type is used as an output type in the “Query” type to fetch individual persons (“getPerson”) and a list of all people (“getAllPeople”).

For mutations, we define a “PersonInput” type using the “input” keyword. This type is used as an input type for the “createPerson” mutation, allowing clients to provide data to create a new person.

By defining the “Person” type as both an output type and an input type, we can reuse the same structure for data retrieval and data creation in our GraphQL API, making the schema more concise and efficient.

error: Content is protected !!