Skip to content

Instantly share code, notes, and snippets.

@nandosola
Last active May 17, 2021 10:46
Show Gist options
  • Save nandosola/2d8fcddd4016068b72683fa21c5e577f to your computer and use it in GitHub Desktop.
Save nandosola/2d8fcddd4016068b72683fa21c5e577f to your computer and use it in GitHub Desktop.
A testable Go Service with repository (storage + finders)
package main
import (
"fmt"
)
type Thing struct {
Uuid string
Description string
}
type Store interface {
findRawThing(string, string)(string, error)
}
///====
type TestStore struct {}
func NewTestStore(config string) (*TestStore, error){
return &TestStore{}, nil
}
func (ts *TestStore) findRawThing(uuid string, another string)(string, error) {
fmt.Println(another)
return "this is a raw TEST thing", nil
}
//*****
type RealStore struct {
config string
}
func NewRealStore(config string) (*RealStore, error){
return &RealStore{config: config}, nil
}
func (ts *RealStore) findRawThing(uuid string, another string)(string, error) {
fmt.Println(another)
return "this is a raw thing coming from REAL db", nil
}
///====
type ThingRepository interface {
FindThing(string)(*Thing, error)
}
type Thinger struct {}
func (tr Thinger) FindThing(uuid string) func(Store)(*Thing, error) {
return func(st Store)(*Thing, error) {
rawThing, _ := st.findRawThing(uuid, "another_param")
return &Thing{Uuid: uuid, Description: rawThing}, nil
}
}
//====
type Repository struct {
store Store
thinger Thinger
}
func (tr *Repository) FindThing(uuid string)(*Thing, error) {
return tr.thinger.FindThing(uuid)(tr.store)
}
func NewTestThingRepository(config string)(ThingRepository, error) {
testStore, _ := NewTestStore(config)
return &Repository{store: testStore, thinger: Thinger{}}, nil
}
func NewRealThingRepository(config string)(ThingRepository, error) {
realStore, _ := NewRealStore(config)
return &Repository{store: realStore, thinger: Thinger{}}, nil
}
//====
func main() {
testRepo, _ := NewTestThingRepository("config")
aTestThing, _ := testRepo.FindThing("c0ff33b4be")
fmt.Printf("TEST_REPO => %+v\n", aTestThing)
realRepo, _ := NewRealThingRepository("config")
aRealThing, _ := realRepo.FindThing("c0ff33b4be")
fmt.Printf("REAL_REPO => %+v\n", aRealThing)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment