Before we dive into the wonderful world of gRPC, let’s take the time to implement the business critical part of our gRPC service first.
Implementation
Let’s start off by creating a rocket.go
file within our internal/rocket/
directory that we created in the last video.
package rocket
// Rocket - should contain things like the ID for the rocket,
// the name for the rocket and the type of rocket. I.e. Falcon Heavy
type Rocket struct {
ID string
Name string
Type string
}
// Service - our rocket service, used for updating our
// rocket inventory
type Service struct {
}
// New - returns a new rocket service
func New() Service {
return Service{}
}
An Interface Defining our Store
We want to define an interface
that models how we want to store rockets within our database. By defining this here, we effectively enable ourselves to easily swap out our data storage system as long as it adheres to this particular interface.
// Store - defines the interface we need to satisfy for our
// service to work correctly
type Store interface {
GetRocketByID(id string) (Rocket, error)
InsertRocket(rkt Rocket) (Rocket, error)
DeleteRocket(id string) error
}
With this in place, we can then update our Service
struct and add a Store which we then pass in within a New
function:
// Service - our rocket service, used for updating our
// rocket inventory
type Service struct {
Store Store
}
// New - returns a new rocket service
func New(store Store) Service {
return Service{
Store: store,
}
}
We can now set about implementing our functions to use this new store interface implementation:
// GetRocketByID - retrieves a rocket from the store by ID
func (s Service) GetRocketByID(id string) (Rocket, error) {
rkt, err := s.Store.GetRocketByID(id)
if err != nil {
return Rocket{}, err
}
return rkt, nil
}
// AddRocket - Adds a rocket to our store
func (s Service) AddRocket(rkt Rocket) (Rocket, error) {
rkt, err := s.Store.InsertRocket(rkt)
if err != nil {
return Rocket{}, err
}
return rkt, nil
}
// DeleteRocket - deletes a rocket - most likely rapid
// unscheduled disassembly
func (s Service) DeleteRocket(id string) error {
err := s.Store.DeleteRocket(id)
if err != nil {
return err
}
return nil
}
We now have a fully implemented Rocket service. I’m not going to do a full CRUD implementation as that isn’t the point of this course.
Conclusion
Awesome, so in this video, we have think we have a successful implementation for our Rocket service. Think being the keyword in that sentence.
As it stands, we have no tests yet for this service so we need to set about solving that problem quickly. We’ll be tackling this particular issue in the next video in this course.