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 at multiple places.
Example:
input PersonInput {
id: String!
name: String
address: String
}
type Person {
id: String!
name: String
address: String
}
And 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 no way to specify "on Person/PersonInput".
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.
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 overresource
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.
Take a look this: https://www.apollographql.com/docs/guides/schema-design.html
For my opinions, there are two options:
Use
interface
to define your commonschema
fieldsUse
es6
string template syntax. Use it like${common}