2020-03-12 16:41:30 +03:00
|
|
|
package scope
|
|
|
|
|
|
|
|
import (
|
2020-09-17 15:41:49 +03:00
|
|
|
"context"
|
2020-03-12 16:41:30 +03:00
|
|
|
"fmt"
|
|
|
|
|
2020-08-19 17:47:17 +03:00
|
|
|
"github.com/unistack-org/micro/v3/store"
|
2020-03-12 16:41:30 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// Scope extends the store, applying a prefix to each request
|
|
|
|
type Scope struct {
|
|
|
|
store.Store
|
|
|
|
prefix string
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewScope returns an initialised scope
|
|
|
|
func NewScope(s store.Store, prefix string) Scope {
|
|
|
|
return Scope{Store: s, prefix: prefix}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Scope) Options() store.Options {
|
|
|
|
o := s.Store.Options()
|
2020-04-06 18:45:55 +03:00
|
|
|
o.Table = s.prefix
|
2020-03-12 16:41:30 +03:00
|
|
|
return o
|
|
|
|
}
|
|
|
|
|
2020-09-17 15:41:49 +03:00
|
|
|
func (s *Scope) Read(ctx context.Context, key string, opts ...store.ReadOption) ([]*store.Record, error) {
|
2020-03-12 16:41:30 +03:00
|
|
|
key = fmt.Sprintf("%v/%v", s.prefix, key)
|
2020-09-17 15:41:49 +03:00
|
|
|
return s.Store.Read(ctx, key, opts...)
|
2020-03-12 16:41:30 +03:00
|
|
|
}
|
|
|
|
|
2020-09-17 15:41:49 +03:00
|
|
|
func (s *Scope) Write(ctx context.Context, r *store.Record, opts ...store.WriteOption) error {
|
2020-03-12 16:41:30 +03:00
|
|
|
r.Key = fmt.Sprintf("%v/%v", s.prefix, r.Key)
|
2020-09-17 15:41:49 +03:00
|
|
|
return s.Store.Write(ctx, r, opts...)
|
2020-03-12 16:41:30 +03:00
|
|
|
}
|
|
|
|
|
2020-09-17 15:41:49 +03:00
|
|
|
func (s *Scope) Delete(ctx context.Context, key string, opts ...store.DeleteOption) error {
|
2020-03-12 16:41:30 +03:00
|
|
|
key = fmt.Sprintf("%v/%v", s.prefix, key)
|
2020-09-17 15:41:49 +03:00
|
|
|
return s.Store.Delete(ctx, key, opts...)
|
2020-03-12 16:41:30 +03:00
|
|
|
}
|
|
|
|
|
2020-09-17 15:41:49 +03:00
|
|
|
func (s *Scope) List(ctx context.Context, opts ...store.ListOption) ([]string, error) {
|
2020-03-12 16:41:30 +03:00
|
|
|
var lops store.ListOptions
|
|
|
|
for _, o := range opts {
|
|
|
|
o(&lops)
|
|
|
|
}
|
|
|
|
|
|
|
|
key := fmt.Sprintf("%v/%v", s.prefix, lops.Prefix)
|
|
|
|
opts = append(opts, store.ListPrefix(key))
|
|
|
|
|
2020-09-17 15:41:49 +03:00
|
|
|
return s.Store.List(ctx, opts...)
|
2020-03-12 16:41:30 +03:00
|
|
|
}
|