-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
68 lines (54 loc) · 1.46 KB
/
db.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
package db
import (
"errors"
"sync"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
)
var (
FailedToMarshalItem = "Failed to marshal item"
ErrorCouldNotPutItem = "Error, failed to enter new item"
)
/**
* dynamo client provider uses mutex to ensure safe concurrent operations
- read mutex ensures that no other process writes to the the same table name
- write mutex ensures that no other process
**/
type DynamoClient[T interface{}] struct {
tableName string
client dynamodbiface.DynamoDBAPI
mu sync.Mutex
errChan chan error
}
func NewDynamoClient[T interface{}](dynamodbSession dynamodbiface.DynamoDBAPI, tableName string) DynamoClient[T] {
var d DynamoClient[T]
d.tableName = tableName
d.client = dynamodbSession
return d
}
/**
* How do I customize the construction this type parameter list
to use the generic values that I create?
**/
func (d *DynamoClient[T])InsertInto(item T) error {
attributeValues, err := dynamodbattribute.MarshalMap(item)
if err != nil {
return errors.New(FailedToMarshalItem)
}
go func() {
defer d.mu.Unlock()
d.mu.Lock()
input := &d.client.PutItemInput{
Item: attributeValues,
TableName: aws.String(d.tableName),
}
d.errChan <- d.client.putItem(input)
}()
err = <- d.errChan
if err != nil {
return errors.New(ErrorCouldNotPutItem)
}
return nil
}