Files
sendico/api/payments/methods/internal/service/methods/util.go
2026-02-13 02:33:22 +01:00

84 lines
2.2 KiB
Go

package methods
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/tech/sendico/pkg/api/routers/gsresponse"
"github.com/tech/sendico/pkg/merrors"
"github.com/tech/sendico/pkg/mlogger"
"github.com/tech/sendico/pkg/model"
"github.com/tech/sendico/pkg/mservice"
paginationv2 "github.com/tech/sendico/pkg/proto/common/pagination/v2"
"go.mongodb.org/mongo-driver/v2/bson"
)
func autoError[T any](ctx context.Context, logger mlogger.Logger, err error) (*T, error) {
return gsresponse.Execute(ctx, gsresponse.Auto[T](logger, mservice.PaymentMethods, err))
}
func parseObjectID(value, field string) (bson.ObjectID, error) {
trimmed := strings.TrimSpace(value)
if trimmed == "" {
return bson.NilObjectID, merrors.InvalidArgument(fmt.Sprintf("%s is required", field), field)
}
ref, err := bson.ObjectIDFromHex(trimmed)
if err != nil {
return bson.NilObjectID, merrors.InvalidArgument(fmt.Sprintf("%s must be a valid object id", field), field)
}
return ref, nil
}
func decodePaymentMethod(data []byte) (*model.PaymentMethod, error) {
if len(data) == 0 {
return nil, merrors.InvalidArgument("payment_method_json is required", "payment_method_json")
}
res := &model.PaymentMethod{}
if err := json.Unmarshal(data, res); err != nil {
return nil, merrors.InvalidArgumentWrap(err, "failed to decode payment method", "payment_method_json")
}
return res, nil
}
func encodePaymentMethod(pm *model.PaymentMethod) ([]byte, error) {
if pm == nil {
return nil, merrors.InvalidArgument("payment method is required")
}
payload, err := json.Marshal(pm)
if err != nil {
return nil, merrors.InternalWrap(err, "failed to encode payment method")
}
return payload, nil
}
func toModelCursor(cursor *paginationv2.ViewCursor) *model.ViewCursor {
if cursor == nil {
return nil
}
res := &model.ViewCursor{}
hasAny := false
if limit := cursor.GetLimit(); limit != nil {
v := limit.GetValue()
res.Limit = &v
hasAny = true
}
if offset := cursor.GetOffset(); offset != nil {
v := offset.GetValue()
res.Offset = &v
hasAny = true
}
if archived := cursor.GetIsArchived(); archived != nil {
v := archived.GetValue()
res.IsArchived = &v
hasAny = true
}
if !hasAny {
return nil
}
return res
}