Skip to content

Commit 3c49487

Browse files
authored
fix: add validations on grant input (#3433)
1 parent 2f9f4f4 commit 3c49487

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

openmeter/credit/errors.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package credit
2+
3+
import "github.com/openmeterio/openmeter/pkg/models"
4+
5+
const ErrCodeGrantAmountMustBePositive models.ErrorCode = "grant_amount_must_be_positive"
6+
7+
var ErrGrantAmountMustBePositive = models.NewValidationIssue(
8+
ErrCodeGrantAmountMustBePositive,
9+
"amount must be positive",
10+
models.WithFieldString("amount"),
11+
)
12+
13+
const ErrCodeEffectiveAtMustBeSet models.ErrorCode = "grant_effective_at_must_be_set"
14+
15+
var ErrGrantEffectiveAtMustBeSet = models.NewValidationIssue(
16+
ErrCodeEffectiveAtMustBeSet,
17+
"effective at must be set",
18+
models.WithFieldString("effectiveAt"),
19+
)

openmeter/credit/grant.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,24 @@ type CreateGrantInput struct {
3434
Recurrence *timeutil.Recurrence
3535
}
3636

37+
func (i CreateGrantInput) Validate() error {
38+
if i.Amount <= 0 {
39+
return ErrGrantAmountMustBePositive.WithAttr("amount", i.Amount)
40+
}
41+
if i.EffectiveAt.IsZero() {
42+
return ErrGrantEffectiveAtMustBeSet.WithAttr("effective_at", i.EffectiveAt)
43+
}
44+
return nil
45+
}
46+
3747
func (m *connector) CreateGrant(ctx context.Context, ownerID models.NamespacedID, input CreateGrantInput) (*grant.Grant, error) {
3848
ctx, span := m.Tracer.Start(ctx, "credit.CreateGrant", cTrace.WithOwner(ownerID))
3949
defer span.End()
4050

51+
if err := input.Validate(); err != nil {
52+
return nil, err
53+
}
54+
4155
return transaction.Run(ctx, m.GrantRepo, func(ctx context.Context) (*grant.Grant, error) {
4256
tx, err := entutils.GetDriverFromContext(ctx)
4357
if err != nil {

0 commit comments

Comments
 (0)