Practical example of GraphQL schema design
In this article, we will create a GraphQL schema for a notes app. We will create a schema for creating, updating, deleting and fetching notes. We will then extend the schema to support pagination, custom reports and custom mutations.
type Note {
id: ID!
title: String!
content: String!
categoryId: ID!
tags: [String!]!
}
Let's create a schema for creating a note,
type Mutation {
createNote(
title: String!
content: String!
categoryId: ID!
tags: [String!]!
): Note!
}
Let's create a schema for updating a note,
type Mutation {
updateNote(
id: ID!
title: String!
content: String!
categoryId: ID!
tags: [String!]!
): Note!
}
Let's create a schema for deleting a note,
type Mutation {
deleteNote(id: ID!): Boolean!
}
Let's create a schema for fetching a note,
type Query {
noteById(id: ID!): Note!
}
Let's create a schema for fetching notes by category,
type Query {
notesByCategory(categoryId: ID!): [Note!]!
}
Let's create a schema for fetching notes by tags,
type Query {
notesByTags(tags: [String!]!): [Note!]!
}
Let's create a schema for fetching all notes and support paginated list,
type Query {
notes(page: Int, limit: Int): [Note!]!
}
Let's create custom reports on notes,
type Query {
notesReport: NotesReport!
reportsByCategory: [CategoryReport!]!
}
type NotesReport {
totalNotes: Int!
totalCategories: Int!
totalTags: Int!
}
type CategoryReport {
categoryId: ID!
totalNotes: Int!
}
Now, let's create dedicated custom mutations to
- update catogory
- add / remove tag
type Mutation {
updateCategory(id: ID!, categoryId: ID!): Note!
addTag(id: ID!, tag: String!): Note!
removeTag(id: ID!, tag: String!): Note!
}
Hope you enjoyed the article and learn how to create and extend your graphql schema for your application needs š