-
Notifications
You must be signed in to change notification settings - Fork 2
/
cosmosdb.go
100 lines (82 loc) · 2.42 KB
/
cosmosdb.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package azure
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)
type CosmosDBClient struct {
containerClient *azcosmos.ContainerClient
}
func NewCosmosDBClient(account string, db string, container string, cred azcore.TokenCredential) (*CosmosDBClient, error) {
endpoint := fmt.Sprintf("https://%s.documents.azure.com:443/", account)
client, err := azcosmos.NewClient(endpoint, cred, nil)
if err != nil {
return nil, err
}
containerClient, err := client.NewContainer(db, container)
if err != nil {
return nil, err
}
return &CosmosDBClient{
containerClient,
}, nil
}
type CosmosDBContainerClient[T any] struct {
client *azcosmos.ContainerClient
partitionKey string
ttl *int
}
type cosmosDBEntry[T any] struct {
Id string `json:"id"`
ParitionKey string `json:"partition_key"`
TTL *int `json:"ttl"`
Value T `json:"value"`
}
func NewCosmosDBContainerClient[T any](cosmosDBClient *CosmosDBClient, partitionKey string, ttl *int) (*CosmosDBContainerClient[T], error) {
return &CosmosDBContainerClient[T]{
client: cosmosDBClient.containerClient,
partitionKey: partitionKey,
ttl: ttl,
}, nil
}
func (client *CosmosDBContainerClient[T]) getId(key string) string {
return fmt.Sprintf("%s-%s", client.partitionKey, key)
}
func (client *CosmosDBContainerClient[T]) Get(ctx context.Context, key string) (*T, error) {
item, err := client.client.ReadItem(ctx, azcosmos.NewPartitionKeyString(client.partitionKey), client.getId(key), &azcosmos.ItemOptions{})
isNotFound := err != nil && strings.Contains(err.Error(), "404 Not Found")
if err != nil && !isNotFound {
return new(T), err
}
if isNotFound {
return nil, nil
}
if len(item.Value) == 0 {
return nil, nil
}
entry := &cosmosDBEntry[T]{}
err = json.Unmarshal(item.Value, entry)
if err != nil {
return new(T), err
}
return &entry.Value, nil
}
func (client *CosmosDBContainerClient[T]) Set(ctx context.Context, key string, value T) error {
b, err := json.Marshal(cosmosDBEntry[T]{
Id: client.getId(key),
ParitionKey: client.partitionKey,
TTL: client.ttl,
Value: value,
})
if err != nil {
return err
}
_, err = client.client.UpsertItem(ctx, azcosmos.NewPartitionKeyString(client.partitionKey), b, &azcosmos.ItemOptions{})
if err != nil {
return err
}
return nil
}