25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →

Defining the Comment Service

February 13, 2021
Elliot Forbes

Elliot Forbes

Course Instructor

Hey Gophers! My name is Elliot and I'm the creator of TutorialEdge and I've been working with Go systems for roughly 5 years now.

Now that we have our database setup, we have everything we need to start implementing our comment service and build it in a test-driven way.

We’ll start off by defining the interface for our comment service:

package comment

import (
	"time"

	"github.com/jinzhu/gorm"
)

// Service - our comment service
type Service struct {
	DB *gorm.DB
}

// CommentService -
type CommentService interface {
}

// NewService - returns a new comments service
func NewService(db *gorm.DB) *Service {
	return &Service{
		DB: db,
	}
}

Next, we’ll need to define the methods that we want to be part of this service and we’ll also need to define the struct for our Comment object:

package comment

import (
	"time"

	"github.com/jinzhu/gorm"
)

// Service - our comment service
type Service struct {
	DB *gorm.DB
}

// Comment -
type Comment struct {
	gorm.Model
	Slug    string
	Body    string
	Author  string
	Created time.Time
}

// CommentService -
type CommentService interface {
	GetComment(ID uint) (Comment, error)
	PostComment(comment Comment) (Comment, error)
	UpdateComment(ID uint, newComment Comment) (Comment, error)
	DeleteComment(ID uint) error
	GetAllComments() ([]Comment, error)
}

// NewService - returns a new comments service
func NewService(db *gorm.DB) *Service {
	return &Service{
		DB: db,
	}
}

In the next video, we’ll be implementing the tests that will ensure the implementation of our service is correct.