15
Schema first workflows for Graphql development using codegen and Typescript
A strictly typed schema is one of the great benefits of using Graphql. This schema acts as a contract between the backend and the frontend. When working on products that use Graphql as the backend API layer, I observed 2 types of working arrangements between team members :
- Same developer owns the backend work and the front end work. In this scenario the graphql schema evolves alongside the front end code and requirements.
- Multiple (2 or more) developers of same or different teams collaborate on different parts of frontend and backend
This write-up aims to address the second point where developers working on different parts of the app or feature need to do the following things:
- Understand the UI needs
- Understand the data needs of the UI
- Define a Graphql schema that acts as a data contract between frontend and Graphql code.
- Repeat #3 if there is a change in #1 and/or #2
This way of working is not new. Same can be applied if the API speaks REST (via a Swagger Spec) or gRPC (via ProtoBuf definition). We will focus only for the case where Graphql is the technology chosen.
Lets imagine a simple Graphql Schema that defines data and operation for a Super Hero and Villain catalogue
enum Affiliation {
GOOD
EVIL
UNDECIDED
}
type Character {
id: ID!
name: String!
affiliation: Affiliation!
rank: Int!
}
type Query {
characters: [Character]!
character(id: ID!): Character!
}
input NewCharacterInput {
name: String!
affiliation: Affiliation!
rank: Int!
}
input CharacterUpdateInput {
id: ID!
name: String
affiliation: Affiliation
rank: Int
}
type Mutation {
addCharacter(newCharacter: NewCharacterInput!): Character!
updateCharacter(update: CharacterUpdateInput!): Character!
}
type Subscription {
characterAdded: Character!
}
Lets assume we want to build the front end using React and Typescript. We have chosen to use Apollo as the library to talk to the API.
✨✨✨✨
🦾 Enter Graphql Code Generator
On the backend it is paramount that we abide by the Graphql schema as the contract and use that contract as the basis for ensuring the type safety of the request
, response
and resolver
types in our graphql code.
✨✨✨✨
🦾 Once again Graphql Code Generator saves a lot of work for us
15