20
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 :
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:
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
✨✨✨✨
🦾 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
✨✨✨✨
🦾 Once again Graphql Code Generator saves a lot of work for us
request
, response
and resolver
types in our graphql code.✨✨✨✨
🦾 Once again Graphql Code Generator saves a lot of work for us
20