Skip to content

Commit 5ad0c0f

Browse files
committed

File tree

4 files changed

+59
-0
lines changed

4 files changed

+59
-0
lines changed

extra/usagecalculator/features.go

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package usagecalculator
2+
3+
import (
4+
"errors"
5+
"github.com/cloudimpl/next-coder-sdk/polycode"
6+
)
7+
8+
func CreateFeature(ctx polycode.ServiceContext, feature Feature) error {
9+
featuresCol := ctx.Db().Collection("polycode_Features")
10+
return featuresCol.InsertOne(feature)
11+
}
12+
13+
func ConsumeFeature(ctx polycode.ServiceContext, id string, count int) (Feature, error) {
14+
featuresCol := ctx.Db().Collection("polycode_Features")
15+
16+
var feature Feature
17+
exist, err := featuresCol.GetOne(id, &feature)
18+
if err != nil {
19+
return Feature{}, err
20+
}
21+
22+
if !exist {
23+
return Feature{}, errors.New("feature not available")
24+
}
25+
26+
consumed := float64(count) * feature.UnitCost
27+
if consumed > feature.Remaining {
28+
return Feature{}, errors.New("not enough credit to use feature")
29+
}
30+
31+
feature.Used += consumed
32+
feature.Remaining -= consumed
33+
34+
err = featuresCol.UpdateOne(feature)
35+
if err != nil {
36+
return Feature{}, err
37+
}
38+
39+
return feature, nil
40+
}

extra/usagecalculator/models.go

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package usagecalculator
2+
3+
type Feature struct {
4+
Id string `polycode:"id" json:"id"`
5+
Name string `json:"name"`
6+
Group string `json:"group"`
7+
UnitCost float64 `json:"unitCost"`
8+
Total float64 `json:"total"`
9+
Remaining float64 `json:"remaining"`
10+
Used float64 `json:"used"`
11+
}

polycode/client.go

+4
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,10 @@ func (sc *ServiceClient) IncrementCounter(sessionId string, req Counter) (Counte
367367
return res, err
368368
}
369369

370+
func (sc *ServiceClient) Acknowledge(sessionId string) error {
371+
return executeApiWithoutResponse(sc.httpClient, sc.baseURL, sessionId, "v1/context/acknowledge", nil)
372+
}
373+
370374
func executeApiWithoutResponse(httpClient *http.Client, baseUrl string, sessionId string, path string, req any) error {
371375
log.Printf("client: exec api without response from %s with session id %s", path, sessionId)
372376

polycode/context.go

+4
Original file line numberDiff line numberDiff line change
@@ -148,3 +148,7 @@ func (s ContextImpl) IncrementCounter(req Counter) (Counter, error) {
148148
func (s ContextImpl) Logger() Logger {
149149
return s.logger
150150
}
151+
152+
func (s ContextImpl) Acknowledge() error {
153+
return s.serviceClient.Acknowledge(s.sessionId)
154+
}

0 commit comments

Comments
 (0)