-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcosmosclient.go
89 lines (73 loc) · 1.91 KB
/
cosmosclient.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
package main
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
"os"
)
var (
dbName = "bookstore"
containerName = "books"
sampleBook = Book{
Id: "000000001",
Title: "Computer Science",
Price: 100.00,
}
)
func GetClient() *azcosmos.Client {
cosmosDbEndpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT")
if !ok {
panic("AZURE_COSMOS_ENDPOINT could not be found")
}
cosmosDbKey, ok := os.LookupEnv("AZURE_COSMOS_KEY")
if !ok {
panic("AZURE_COSMOS_KEY could not be found")
}
cred, _ := azcosmos.NewKeyCredential(cosmosDbKey)
client, err := azcosmos.NewClientWithKey(cosmosDbEndpoint, cred, nil)
if err != nil {
panic(err)
}
return client
}
func GetDataBase() *azcosmos.DatabaseClient {
client := GetClient()
db, err := client.NewDatabase(dbName)
if err != nil {
panic(err)
}
return db
}
func GetContainer() *azcosmos.ContainerClient {
client := GetClient()
container, err := client.NewContainer(dbName, containerName)
if err != nil {
panic(err)
}
return container
}
func InitializeDatabaseAndContainer() {
client := GetClient()
databaseProperties := azcosmos.DatabaseProperties{ID: dbName}
databaseResponse, err := client.CreateDatabase(context.Background(), databaseProperties, nil)
if err != nil {
panic(err)
}
database, err := client.NewDatabase(dbName)
if err != nil {
panic(err)
}
fmt.Printf("Database created. ActivityId %s\r\n", databaseResponse.ActivityID)
containerProperties := azcosmos.ContainerProperties{
ID: "books",
PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{
Paths: []string{"/title"},
},
}
throughput := azcosmos.NewManualThroughputProperties(400)
resp, err := database.CreateContainer(context.Background(), containerProperties, &azcosmos.CreateContainerOptions{ThroughputProperties: &throughput})
if err != nil {
panic(err)
}
fmt.Printf("Container created. ActivityId %s\r\n", resp.ActivityID)
}