GraphQL Schema Definition
Table of contents
No headings in the article.
This article is part of a tutorial series on building GraphQL API with Go and PostgresQL. Please refer to it as this is the third part of the series.
A GraphQL schema describes the the data (objects, fields) a client can access. Schemas enable generation, validation and type safety for APIs. It also includes the queries and mutations functions that that the client can use to read and write data from the GraphQL server. In REST's CRUD terminology, create, update and delete is analogous to GraphQL's mutation while read falls in line with query.
There are five default scalar types; Int , Float , String , Boolean , and ID. Though helpful when it comes to type safety, the default types are not elaborate enough to cover every data situation. For example, GraphQL uses seconds internally. The implication is that GraphQL will return a long line of seconds in strings to the client even if your database stored it in a readable format. gqlgen, the Go GraphQL package we are using in this project has Time, a built-in helper which adheres to time.RFC3339Nano for date time use cases. This tells us that we can go beyond the default types and build our own custom data types.
For an intensive guide on how to write GraphQL schema, refer to this.
how gqlgen handles time implementation
The Project
Update graph/user.graphqls, graph/post.graphqls and querymutation.graphqls with the following code snippets.
post.graphqls
scalar Time
type Post {
id: ID!
body: String!
sharedBody: String
image: String
createdAt: Time!
updatedAt: Time!
sharedAt: Time
author: User!
sharedUser: User
likes: User
dislikes: User
tags: Tag
}
type Tag {
id: ID!
name: String!
}
input NewPost {
body: String!
sharedBody: String
image: String
}
user.graphqls
type User {
id: ID!
name: String!
email: String!
password: String!
createdAt: Time!
updatedAt: Time!
}
input NewUser {
name: String!
email: String!
password: String!
confirmpassword: String!
}
querymutation.graphqls
type Query {
post: Post!
posts: [Post!]!
user: User!
users: [User!]!
}
type Mutation {
createPost(input: NewPost!): Post!
createUser(input: NewUser): User!
}
type are used to generate models holding the structure of the data while input refers to the data a client will have to supply to create new objects (e.g a new user or post). Any field having an exclamation mark (!) means the data for that field must be supplied or returned. As earlier said, Query allows us to read data while Mutation allows the creating, updating and deleting of data.
Finally run this gqlgen command to generate models, resolvers and some boring codes from your defined schema.
go run github.com/99designs/gqlgen generate
Check graph/generated/generated.go, graph/querymutation.resolvers.go and graph/model/model_gen.go for the generated contents.