diff options
Diffstat (limited to 'core/state_backend.go')
| -rw-r--r-- | core/state_backend.go | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/core/state_backend.go b/core/state_backend.go new file mode 100644 index 0000000..9f9f397 --- /dev/null +++ b/core/state_backend.go | |||
| @@ -0,0 +1,62 @@ | |||
| 1 | package core | ||
| 2 | |||
| 3 | import ( | ||
| 4 | "context" | ||
| 5 | ) | ||
| 6 | |||
| 7 | type StateBackend interface { | ||
| 8 | // For Framework === | ||
| 9 | // SetCurrentKey will perform in Memory | ||
| 10 | SetCurrentKey(key string) error | ||
| 11 | // GetCurrentKey will perform in Memory | ||
| 12 | GetCurrentKey() string | ||
| 13 | SetCurrentNamespace(namespace any) error | ||
| 14 | GetCurrentNamespace() any | ||
| 15 | |||
| 16 | // For User === | ||
| 17 | // GetValueState will perform in disk | ||
| 18 | GetValueState(ctx context.Context, key string) (ValueState[any], error) | ||
| 19 | } | ||
| 20 | |||
| 21 | type stateBackendKeyType struct{} | ||
| 22 | |||
| 23 | var stateBackendKey stateBackendKeyType | ||
| 24 | |||
| 25 | type typedValueState[T any] struct { | ||
| 26 | inner ValueState[any] | ||
| 27 | } | ||
| 28 | |||
| 29 | func CastValueType[T any](inner ValueState[any]) ValueState[T] { | ||
| 30 | return &typedValueState[T]{inner: inner} | ||
| 31 | } | ||
| 32 | |||
| 33 | func (s *typedValueState[T]) Value(ctx context.Context) (T, error) { | ||
| 34 | val, err := s.inner.Value(ctx) | ||
| 35 | if err != nil { | ||
| 36 | var zero T | ||
| 37 | return zero, err | ||
| 38 | } | ||
| 39 | if val == nil { | ||
| 40 | var zero T | ||
| 41 | return zero, nil | ||
| 42 | } | ||
| 43 | return val.(T), nil | ||
| 44 | } | ||
| 45 | |||
| 46 | func (s *typedValueState[T]) Update(ctx context.Context, newVal T) (T, error) { | ||
| 47 | _, err := s.inner.Update(ctx, newVal) | ||
| 48 | return newVal, err | ||
| 49 | } | ||
| 50 | |||
| 51 | func (s *typedValueState[T]) Clear(ctx context.Context) error { | ||
| 52 | return s.inner.Clear(ctx) | ||
| 53 | } | ||
| 54 | |||
| 55 | func InjectStateBackend(ctx context.Context, state StateBackend) context.Context { | ||
| 56 | return context.WithValue(ctx, stateBackendKey, state) | ||
| 57 | } | ||
| 58 | |||
| 59 | func ExtractStateBackend(ctx context.Context) (StateBackend, bool) { | ||
| 60 | backend, ok := ctx.Value(stateBackendKey).(StateBackend) | ||
| 61 | return backend, ok | ||
| 62 | } | ||
