Store
Package store defines a simple interface for key-value store dependency
injection.
Not all implementations are supposed to provide every method. More importantly,
the consumers should declare their subset of required methods.
The Store interface is not meant to be used directly, but rather to document
how the methods should be implemented. Every application will define a specific
interface with its required methods only.
Peculiarities
Err is for failures
Most of the time, an application needs to react differently to "key not found"
or to "connection lost". This is why Get
and other methods return a boolean
value to indicate if the key was found.
One interesting consequence of this approach is that by discarding the boolean
return, you can get an idempotent version of Delete
:
_, err := s.Delete(ctx, "key to be deleted")
The Collection
To fetch multiple results at once, the GetAll
method accepts a Collection.
The store will call New()
on the collection and call UnmarshalJSON
on the
returned variable.
Given a User
type which implements json.Unmarshaler
, a collection
implementation could resemble to:
type collection []*User
func (c *collection) New() json.Unmarshaler {
u := new(User)
*c = append(*c, u)
return u
}
The interface definition
type Store interface {
Get(ctx context.Context, k string, v json.Unmarshaler) (ok bool, err error)
GetAll(ctx context.Context, c Collection) error
Add(ctx context.Context, v json.Marshaler) (k string, err error)
Set(ctx context.Context, k string, v json.Marshaler) error
SetWithTimeout(ctx context.Context, k string, v json.Marshaler, timeout time.Duration) error
SetWithDeadline(ctx context.Context, k string, v json.Marshaler, deadline time.Time) error
Update(ctx context.Context, k string, v json.Marshaler) (ok bool, err error)
Delete(ctx context.Context, k string) (ok bool, err error)
Ping(ctx context.Context) error
Close() error
}
type Collection interface {
New() json.Unmarshaler
}