Resolver Component Creation for GraphQL

Implement the resolver

We start by registering the service component in the resolver so the resolver can implement the functionalities with the component. We implement the functionalities inside the schema.resolvers.go file.

Create a new blog

Inside the NewBlog() function, we create an implementation to add new blog data.

func (r *mutationResolver) NewBlog(ctx context.Context, input model.NewBlog) (*model.Blog, error) {
    var blog *model.Blog = r.blogService.CreateBlog(input)
    return blog, nil
}

In the code above, the new blog is created with the CreateBlog() function from the service component.

Edit a blog

Inside the EditBlog() function, we create an implementation to edit or update the blog data.

func (r *mutationResolver) EditBlog(ctx context.Context, input model.EditBlog) (*model.Blog, error) {
    blog, err := r.blogService.EditBlog(input)
    if err != nil {
        return &model.Blog{}, err
    }

    return blog, nil
}

In the code above, the new blog is edited with the EditBlog() function from the service component.

Delete a blog

Inside the DeleteBlog() function, we create an implementation to delete blog data.

func (r *mutationResolver) DeleteBlog(ctx context.Context, input model.DeleteBlog) (bool, error) {
    var result bool = r.blogService.DeleteBlog(input)

    return result, nil
}

In the code above, the new blog is deleted with the DeleteBlog() function from the service component.

Get all blog

Inside the Blogs() function, we create an implementation to get all blogs.

func (r *queryResolver) Blogs(ctx context.Context) ([]*model.Blog, error) {
    var blogs []*model.Blog = r.blogService.GetAllBlogs()

    return blogs, nil
}

In the code above, all blog data is retrieved with the GetAllBlogs() function from the service component.

Get blog by ID

Inside the Blog() function, we create an implementation to get the blog by ID.

func (r *queryResolver) Blog(ctx context.Context, id string) (*model.Blog, error) {
    blog, err := r.blogService.GetBlogByID(id)

    if err != nil {
        return &model.Blog{}, err
    }

    return blog, nil
}

In the code above, the blog data is retrieved with the GetBlogByID() function from the service component.

The complete implementation of the resolver component can be seen in the application below:

Get hands-on with 1200+ tech skills courses.