Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share common fields between Input and Type in GraphQL

I was wondering if there's a way to share the common fields between Input and Type in GraphQL so that I don't have to define the same set of fields in multiple places.

Example:

input PersonInput {
    id: String!
    name: String
    address: String
}

type Person {
    id: String!
    name: String
    address: String
}

I know Fragment might be a solution, but if my understanding is correct, using Fragment always requires you to put an ON condition which makes it look like this:

Fragment PersonCommonFields on Person {
    ...
}

There seems to be no way to specify "on Person/PersonInput".

like image 555
wei Avatar asked Aug 30 '18 16:08

wei


People also ask

Is it possible to use inheritance with GraphQL input types?

No, the spec does not allow input types to implement interfaces. And GraphQL type system in general does not define any form of inheritance (the extends keyword adds fields to an existing type, and isn't for inheritance).

What are the 2 most common actions in GraphQL?

From the point of view of the client, the most common GraphQL operations are likely to be queries and mutations.

What is __ Typename in GraphQL?

The __typename field returns the object type's name as a String (e.g., Book or Author ). GraphQL clients use an object's __typename for many purposes, such as to determine which type was returned by a field that can return multiple types (i.e., a union or interface).

Is GraphQL synchronous or asynchronous?

Query and mutation data exchange under GraphQL is synchronous due to the request-response pattern inherent in the HTTP/1.1 protocol. However, GraphQL allows users to receive messages asynchronously when a specific event is raised on the server-side.


Video Answer


1 Answers

GraphQL fragments are for querying, not schema definition.

When I started learning GraphQL I was annoyed by this too because I was still thinking RESTfully. In most cases having the freedom to set certain fields non-nullable or remove them entirely from an input/output type is invaluable.

e.g.

input CreatePersonInput {
  name: String!
  slug: String
  address: String
}

type Person {
  id: ID! # Autogenerated on the server
  name: String!
  slug: String! # Will always exist, either user provided or computed
  # address: String # Omitted for security reasons
}

It may seem like a lot of extra code at first, but the flexibility this brings you over resource based schemas is worth it for long-term projects. I've seen it help out dozens of times.

You should also consider behavior/task-based mutations over resource or "anemic mutations"

I highly recommend learning about fat queries and read about Relay Specification. Even if you don't end up wanting Relay on the client, following some of their rules can really clear up common misconceptions about GraphQL.

like image 53
Seth Avatar answered Oct 04 '22 21:10

Seth