114 lines
2.6 KiB
Go
114 lines
2.6 KiB
Go
package ddb
|
|
|
|
import (
|
|
"context"
|
|
"github.com/aws/aws-sdk-go-v2/aws"
|
|
"github.com/aws/aws-sdk-go-v2/config"
|
|
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
|
|
"github.com/tomas-qstarrs/redimo"
|
|
)
|
|
|
|
type DDB struct {
|
|
*Config
|
|
dynamodbClient *dynamodb.Client
|
|
redimoClient *redimo.Client
|
|
}
|
|
|
|
func Init() {
|
|
ddb.init()
|
|
}
|
|
|
|
var ddb = &DDB{}
|
|
|
|
func (ddb *DDB) init() {
|
|
ddb.initConfig()
|
|
ddb.initClient()
|
|
ddb.initTable()
|
|
}
|
|
|
|
func (ddb *DDB) initConfig() {
|
|
ddb.Config = NewConfig()
|
|
}
|
|
|
|
func (ddb *DDB) initClient() {
|
|
var (
|
|
sdkConfig aws.Config
|
|
err error
|
|
)
|
|
var options []func(*config.LoadOptions) error
|
|
|
|
if ddb.Endpoint.URL != "" || ddb.Endpoint.PartitionID != "" ||
|
|
ddb.Endpoint.SigningRegion != "" {
|
|
options = append(options, config.WithEndpointResolverWithOptions(
|
|
aws.EndpointResolverWithOptionsFunc(
|
|
func(service, region string, _ ...interface{}) (
|
|
aws.Endpoint, error) {
|
|
if service == dynamodb.ServiceID {
|
|
return aws.Endpoint{
|
|
URL: ddb.Endpoint.URL,
|
|
PartitionID: ddb.Endpoint.PartitionID,
|
|
SigningRegion: ddb.Endpoint.SigningRegion,
|
|
}, nil
|
|
}
|
|
return aws.Endpoint{}, &aws.EndpointNotFoundError{}
|
|
},
|
|
),
|
|
))
|
|
}
|
|
|
|
if ddb.Credentials.AccessKeyID != "" || ddb.Credentials.SecretAccessKey != "" ||
|
|
ddb.Credentials.SessionToken != "" || ddb.Credentials.Source != "" {
|
|
options = append(options, config.WithCredentialsProvider(
|
|
aws.CredentialsProviderFunc(
|
|
func(_ context.Context) (aws.Credentials, error) {
|
|
return aws.Credentials{
|
|
AccessKeyID: ddb.Credentials.AccessKeyID,
|
|
SecretAccessKey: ddb.Credentials.SecretAccessKey,
|
|
SessionToken: ddb.Credentials.SessionToken,
|
|
Source: ddb.Credentials.Source,
|
|
}, nil
|
|
},
|
|
),
|
|
))
|
|
}
|
|
sdkConfig, err = config.LoadDefaultConfig(context.Background(), options...)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
ddb.dynamodbClient = dynamodb.NewFromConfig(sdkConfig)
|
|
|
|
redimoClientStruct := redimo.NewClient(
|
|
ddb.dynamodbClient,
|
|
).Table(
|
|
ddb.Table.TableName,
|
|
).Index(
|
|
ddb.Table.IndexName,
|
|
).Attributes(
|
|
ddb.Table.PartitionKey,
|
|
ddb.Table.SortKey,
|
|
ddb.Table.SortKeyNum,
|
|
).TransactionActions(
|
|
ddb.TransactionSize,
|
|
)
|
|
ddb.redimoClient = &redimoClientStruct
|
|
}
|
|
|
|
func (ddb *DDB) initTable() {
|
|
if ok, err := ddb.redimoClient.ExistsTable(); err != nil {
|
|
panic(err)
|
|
} else if !ok {
|
|
if err := ddb.redimoClient.CreateTable(ddb.Provisioned.ReadCapacityUnits, ddb.Provisioned.WriteCapacityUnits); err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func DynamoDBClient() *dynamodb.Client {
|
|
return ddb.dynamodbClient
|
|
}
|
|
|
|
func RedimoClient() *redimo.Client {
|
|
return ddb.redimoClient
|
|
}
|