Search⌘ K

Service Component Creation for GraphQL

Explore how to create a service component for GraphQL applications in Go. Learn to implement CRUD operations such as fetching, creating, updating, and deleting blog data, and how to register the service within the resolver, enabling effective backend functionality.

Create a service component

Before creating a service component, we create a new directory inside the graph directory called service. Then, we add a service component in the service.go.

Go (1.18.2)
package service
import (
"errors"
"github.com/google/uuid"
"go-gql-blogs/graph/model"
)
// BlogService represents service component
type BlogService struct{}
// create a local storage
var storage []*model.Blog
Service component for the application

In the code above, there are two main components:

  • BlogService: Acts as a service component that is used by the resolver.

  • storage: Acts as local storage for the application.

Get all blogs

We create a function to get all blogs called GetAllBlogs.

Go (1.18.2)
// other codes..
func (b *BlogService) GetAllBlogs() []*model.Blog {
return storage
}
Get all blogs

In the code above, the function simply returns all blogs.

Get blog data by

...