From 7051c2b3fc33e43edcf689b3f6c8156155c49afd Mon Sep 17 00:00:00 2001 From: Mariem Baccari Date: Tue, 11 Aug 2026 15:04:18 +0200 Subject: [PATCH] [store] json encoding generics --- pkg/store/store.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/pkg/store/store.go b/pkg/store/store.go index 9544cfb2e..4b87b0a67 100644 --- a/pkg/store/store.go +++ b/pkg/store/store.go @@ -2,6 +2,7 @@ package store import ( "context" + "encoding/json" "io" "github.com/interuss/stacktrace" @@ -31,6 +32,27 @@ type OperationHandler[R any] struct { IsReadOnly bool } +// EncodeJSON is a general-purpose OperationHandler.Encode that marshals the request as JSON. +// TODO: remove once all operations use custom encoders / decoders. +func EncodeJSON(request OperationRequest) ([]byte, error) { + buf, err := json.Marshal(request) + if err != nil { + return nil, stacktrace.Propagate(err, "failed to marshal %q request", request.OperationID()) + } + return buf, nil +} + +// DecodeJSON is a general-purpose OperationHandler.Decode that unmarshals JSON into a new T. +// T must be a pointer to a struct type that implements OperationRequest. +// TODO: remove once all operations use custom encoders / decoders. +func DecodeJSON[T OperationRequest](buf []byte) (OperationRequest, error) { + req := new(T) + if err := json.Unmarshal(buf, req); err != nil { + return nil, stacktrace.Propagate(err, "failed to unmarshal request") + } + return *req, nil +} + // TransactWithResult wraps Store.Transact and casts the result to ResultType, avoiding a cast at every call site. func TransactWithResult[R any, ResultType any](ctx context.Context, store Store[R], request OperationRequest) (ResultType, error) { var empty ResultType