51 lines
1.1 KiB
Go
51 lines
1.1 KiB
Go
package sdk
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
)
|
|
|
|
type Encoder[T any] interface {
|
|
Get(ctx context.Context, key string) (val T, ok bool, meta StateMetadata, err error)
|
|
Set(ctx context.Context, key string, val T) error
|
|
}
|
|
|
|
var _ Encoder[struct{}] = (*JSONStateEncoder[struct{}])(nil)
|
|
|
|
func NewJSONStateEncoder[T any](ctx ExecutionContext) *JSONStateEncoder[T] {
|
|
return &JSONStateEncoder[T]{
|
|
Context: ctx,
|
|
}
|
|
}
|
|
|
|
type JSONStateEncoder[T any] struct {
|
|
Context ExecutionContext
|
|
}
|
|
|
|
func (j JSONStateEncoder[T]) Get(ctx context.Context, key string) (val T, ok bool, meta StateMetadata, err error) {
|
|
var data []byte
|
|
|
|
data, meta, err = j.Context.GetState(ctx, key)
|
|
if err != nil {
|
|
return val, false, StateMetadata{}, err
|
|
}
|
|
|
|
if len(data) == 0 {
|
|
return val, false, meta, nil
|
|
}
|
|
|
|
if err := json.Unmarshal(data, &val); err != nil {
|
|
return val, false, StateMetadata{}, err
|
|
}
|
|
|
|
return val, true, meta, nil
|
|
}
|
|
|
|
func (j JSONStateEncoder[T]) Set(ctx context.Context, key string, val T) error {
|
|
data, err := json.Marshal(val)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return j.Context.SetState(ctx, key, data)
|
|
}
|