djoemo

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 27, 2026 License: GPL-2.0 Imports: 16 Imported by: 0

README

Djoemo library

import "github.com/adjoeio/djoemo"

is a facade library for guregu/dynamo and uses the repository pattern to simplify dynamodb operations (save, update , delete and retrieve) on go structs

Factories

// NewRepository factory method for dynamo repository
NewRepository(dynamoClient dynamodbiface.DynamoDBAPI) RepositoryInterface
// Key factory method to create struct implement key interface
func Key() *key {
    return &key{}
}

// usage 
key := djoemo.Key().
    WithTableName("user").
    WithHashKeyName("UserUUID").
    WithHashKey("123").
    WithRangeKeyName("CreatedAt").
    WithRangeKey(time.Now().Day())

Interfaces

RepositoryInterface:

// WithLog enables logging; it accepts LogInterface as logger
WithLog(log LogInterface)

// WithMetrics enables metrics; it accepts MetricsInterface as metrics publisher
WithMetrics(metricsInterface MetricsInterface)

// WithPrometheusMetrics enables prometheus metrics
WithPrometheusMetrics(registry *prometheus.Registry)

// GetItemWithContext get item; it accepts a key interface that is used to get the table name, hash key and range key if it exists; the output will be given in item
// returns true if item is found, returns false and nil if no item found, returns false and an error in case of error
GetItemWithContext(ctx context.Context, key KeyInterface, item any) (bool, error)

// SaveItemWithContext it accepts a key interface, that is used to get the table name; item is the item to be saved; context which used to enable log with context
// returns error in case of error
SaveItemWithContext(ctx context.Context, key KeyInterface, item any) error

// UpdateWithContext updates item by key; it accepts an expression (Set, SetSet, SetIfNotExists, SetExpr); key is the key to be updated;
// values contains the values that should be used in the update; context which used to enable log with context
// returns error in case of error
UpdateWithContext(ctx context.Context, expression UpdateExpression, key KeyInterface, values map[string]any) error

// UpdateWithUpdateExpressions updates an item with update expressions defined at field level, enabling you to set
// different update expressions for each field. The first key of the updateMap specifies the Update expression to use
// for the expressions in the map
UpdateWithUpdateExpressions(ctx context.Context, key KeyInterface, updateExpressions UpdateExpressions) error

// UpdateWithUpdateExpressionsAndReturnValue updates an item with update expressions defined at field level and returns
// the item, as it appears after the update, enabling you to set different update expressions for each field. The first
// key of the updateMap specifies the Update expression to use for the expressions in the map
UpdateWithUpdateExpressionsAndReturnValue(ctx context.Context, key KeyInterface, item any, updateExpressions UpdateExpressions) error

// ConditionalUpdateWithUpdateExpressionsAndReturnValue updates an item with update expressions and a condition.
// If the condition is met, the item will be updated and returned as it appears after the update.
// The first key of the updateMap specifies the Update expression to use for the expressions in the map
ConditionalUpdateWithUpdateExpressionsAndReturnValue(ctx context.Context, key KeyInterface, item any, updateExpressions UpdateExpressions, conditionExpression string, conditionArgs ...any) (conditionMet bool, err error)

// DeleteItemWithContext item by its key; it accepts key of item to be deleted; context which used to enable log with context
// returns error in case of error
DeleteItemWithContext(ctx context.Context, key KeyInterface) error

// SaveItemsWithContext batch save a slice of items by key; it accepts key of item to be saved; item to be saved; context which used to enable log with context
// returns error in case of error
SaveItemsWithContext(ctx context.Context, key KeyInterface, items any) error

// DeleteItemsWithContext deletes items matching the keys; it accepts array of keys to be deleted; context which used to enable log with context
// returns error in case of error
DeleteItemsWithContext(ctx context.Context, key []KeyInterface) error

// GetItemsWithContext by key; it accepts key of item to get it; context which used to enable log with context
// returns true if items are found, returns false and nil if no items found, returns false and error in case of error
GetItemsWithContext(ctx context.Context, key KeyInterface, out any) (bool, error)

// QueryWithContext by query; it accepts a query interface that is used to get the table name, hash key and range key with its operator if it exists;
// context which used to enable log with context, the output will be given in items
// returns error in case of error
QueryWithContext(ctx context.Context, query QueryInterface, item any) error

// GIndex returns index repository
GIndex(name string) GlobalIndexInterface

// OptimisticLockSaveWithContext saves an item if the version attribute on the server matches the version of the object
OptimisticLockSaveWithContext(ctx context.Context, key KeyInterface, item any) (bool, error)

// ScanIteratorWithContext returns an instance of an iterator that provides methods to use for scanning tables
ScanIteratorWithContext(ctx context.Context, key KeyInterface, searchLimit int64) (IteratorInterface, error)

// ConditionalUpdateWithContext updates an item if the passed expression and condition evaluates to true
ConditionalUpdateWithContext(ctx context.Context, key KeyInterface, item any, expression string, expressionArgs ...any) (bool, error)

// BatchGetItemsWithContext gets multiple items by their keys; it accepts a slice of keys (all from the same table)
// and fills out (pointer to a slice) with any found items.
// returns true if at least one item is found, returns false and nil if no items found, returns false and error in case of error
BatchGetItemsWithContext(ctx context.Context, keys []KeyInterface, out any) (bool, error)

GlobalIndexInterface:

// GetItemWithContext get item from index; it accepts a key interface that is used to get the table name, hash key and range key if it exists;
// context which used to enable log with context; the output will be given in item
// returns true if item is found, returns false and nil if no item found, returns false and an error in case of error
GetItemWithContext(ctx context.Context, key KeyInterface, item interface{}) (bool, error)

// GetItemsWithContext by key from index; it accepts a key interface that is used to get the table name, hash key and range key if it exists;
// context which used to enable log with context, the output will be given in items
// returns true if items are found, returns false and nil if no items found, returns false and error in case of error
GetItemsWithContext(ctx context.Context, key KeyInterface, items interface{}) (bool, error)

// GetItemsWithRangeWithContext same as GetItemsWithContext, but also respects range key
GetItemsWithRangeWithContext(ctx context.Context, key KeyInterface, items interface{}) (bool, error)

// QueryWithContext by query; it accepts a query interface that is used to get the table name, hash key and range key with its operator if it exists;
// context which used to enable log with context, the output will be given in items
// returns error in case of error
QueryWithContext(ctx context.Context, query QueryInterface, item interface{}) error

KeyInterface: Acts as adapter between dynamo db table key and golang model.

// TableName returns dynamo table name
TableName() string

// HashKeyName returns the name of hash key if it exists
HashKeyName() *string

// RangeKeyName returns the name of range key if it exists
RangeKeyName() *string

// HashKey returns the hash key value
HashKey() interface{}

// RangeKey returns the range key value
RangeKey() interface{}

LogInterface: To support debug, it's necessary to provide a logger with this interface.

// WithFields adds fields from map string interface to logger
WithFields(fields map[string]interface{}) LogInterface

// WithField adds a single field to logger
WithField(field string, value any) LogInterface

// WithContext adds context to logger
WithContext(ctx context.Context) LogInterface

// Info logs info
Info(message string )

// Warn logs warning
Warn(message string )

// Error logs error
Error(message string )

MetricsInterface: To support metrics, it's necessary to provide a metrics publisher with this interface.

// Record publishes metrics for an operation
Record(ctx context.Context, caller string, key KeyInterface, duration time.Duration, err *error)

Usage

Get example:

// enable log by passing logger interface
repository.WithLog(logInterface)

// enable metrics by passing metrics interface
repository.WithMetrics(metricsInterface)

user := &User{}
// use factory to create dynamo key interface
key := djoemo.Key().
    WithTableName("user").
    WithHashKeyName("UserUUID").
    WithHashKey("123")

// optional:
// create context with source label for metrics (increase observability)
ctx = WithSourceLabel(ctx, "FooBarAPI")

// get item
found, err := repository.GetItemWithContext(
    ctx,
	key,
	user)
if err != nil {
    fmt.Println(err.Error())
}

if !found {
    fmt.Println("user not found")
}

notes

  • The operation will not fail, if publish of metrics returns an error. If the logger is enabled, it will just log the error.

For more examples see examples/example.go .

Documentation

Index

Constants

View Source
const (
	StatusSuccess = "success"
	StatusFailure = "failure"

	OpCommit = "commit"
	OpUpdate = "update"
	OpRead   = "read"
	OpDelete = "delete"
)
View Source
const (
	Equal          Operator = "EQ"
	NotEqual                = "NE"
	Less                    = "LT"
	LessOrEqual             = "LE"
	Greater                 = "GT"
	GreaterOrEqual          = "GE"
	BeginsWith              = "BEGINS_WITH"
	Between                 = "BETWEEN"
)

Operators used for comparing against the range key.

View Source
const DayFormat = "2006-01-02"

DayFormat is the format for a day

View Source
const DayHourFormat = "2006-01-02 15"

DayHourFormat is the format for a day

View Source
const MonthFormat = "2006-01"

MonthFormat is the format for a month

View Source
const RFC3339Milli = "2006-01-02T15:04:05.999Z07:00"

RFC3339Milli with millisecond precision

View Source
const TableName string = "TableName"
View Source
const TenYears = time.Duration(time.Hour * 24 * 365 * 10)

TenYears ...

View Source
const TimeFormatStandard = "2006-01-02T15:04:05.000Z07:00"

TimeFormatStandard is a mysql time.Time type with some helper functions

Variables

View Source
var ErrInvalidBatchRequest = errors.New("batch request with multiple tables")

ErrInvalidBatchRequest batch request should be for same table

View Source
var ErrInvalidHashKeyName = errors.New("invalid hash key name")

ErrInvalidHashKeyName hash key name is invalid error

View Source
var ErrInvalidHashKeyValue = errors.New("invalid hash key value")

ErrInvalidHashKeyValue hash key value is invalid error

View Source
var ErrInvalidPointerSliceType = errors.New("invalid type expected pointer of slice")

ErrInvalidPointerSliceType should be pointer of slice error

View Source
var ErrInvalidSliceType = errors.New("invalid type expected slice")

ErrInvalidSliceType interface should be slice error

View Source
var ErrInvalidTableName = errors.New("invalid table name")

ErrInvalidTableName table name is invalid error

View Source
var ErrNoItemFound = errors.New("no item found")

ErrNoItemFound item not found error

View Source
var Now = func() DjoemoTime {
	t := time.Now()

	t = t.Round(0)
	return DjoemoTime{Time: t}
}

Now returns the current local time.

Functions

func AddMetrics added in v0.3.0

func AddMetrics(ctx context.Context, key, value string) context.Context

func GetLabelsFromContext added in v0.3.0

func GetLabelsFromContext(ctx context.Context) map[string]string

func InterfaceToArrayOfInterface

func InterfaceToArrayOfInterface(sliceOfItems interface{}) ([]interface{}, error)

InterfaceToArrayOfInterface transforms interface of slice to slice of interfaces

func IsPointerOFSlice

func IsPointerOFSlice(item interface{}) bool

func Key

func Key() *key

Key factory method to create struct that implements key interface

func NewPrometheusMetrics added in v0.3.0

func NewPrometheusMetrics(registry *prometheus.Registry) *prometheusmetrics

func Query

func Query() *query

Key factory method to create struct that implements key interface

func WithSourceLabel added in v0.3.0

func WithSourceLabel(ctx context.Context, value string) context.Context

WithSourceLabel is a label to tag buisness logic as default metrics are aggregated for CURD operations to reduce cardinality

Types

type DjoemoTime

type DjoemoTime struct {
	time.Time
}

DjoemoTime ...

func Date

func Date(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) DjoemoTime

Date returns the Time corresponding to

yyyy-mm-dd hh:mm:ss + nsec nanoseconds

func (*DjoemoTime) MarshalDynamoDBAttributeValue

func (dt *DjoemoTime) MarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error

MarshalDynamoDBAttributeValue ...

func (DjoemoTime) MarshalJSON

func (dt DjoemoTime) MarshalJSON() ([]byte, error)

MarshalJSON ...

func (*DjoemoTime) UnmarshalDynamoDBAttributeValue

func (dt *DjoemoTime) UnmarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error

UnmarshalDynamoDBAttributeValue ...

func (*DjoemoTime) UnmarshalJSON

func (dt *DjoemoTime) UnmarshalJSON(p []byte) error

UnmarshalJSON checks before unmarshal it if a json timestamp is typical adjoe one format

type GlobalIndex

type GlobalIndex struct {
	// contains filtered or unexported fields
}

GlobalIndex models a global secondary index used in a query

func (GlobalIndex) GetItemWithContext

func (gi GlobalIndex) GetItemWithContext(ctx context.Context, key KeyInterface, item any) (bool, error)

GetItemWithContext item; it needs a key interface that is used to get the table name, hash key, and the range key if it exists; output will be contained in item; context is optional param, which used to enable log with context

func (GlobalIndex) GetItemsWithContext

func (gi GlobalIndex) GetItemsWithContext(ctx context.Context, key KeyInterface, items any) (bool, error)

GetItemsWithContext queries multiple items by key (hash key) and returns it in the slice of items items

func (GlobalIndex) GetItemsWithRangeWithContext added in v0.2.0

func (gi GlobalIndex) GetItemsWithRangeWithContext(ctx context.Context, key KeyInterface, items any) (bool, error)

GetItemsWithRangeWithContext queries multiple items by key (hash key) and returns it in the slice of items respecting the range key

func (GlobalIndex) QueryWithContext

func (gi GlobalIndex) QueryWithContext(ctx context.Context, query QueryInterface, item any) (err error)

QueryWithContext by query; it accepts a query interface that is used to get the table name, hash key and range key with its operator if it exists; context which used to enable log with context, the output will be given in items returns error in case of error

func (*GlobalIndex) WithLog added in v0.3.0

func (gi *GlobalIndex) WithLog(log LogInterface)

WithLog enables logging; it accepts LogInterface as logger

func (*GlobalIndex) WithMetrics added in v0.3.0

func (gi *GlobalIndex) WithMetrics(metricsInterface MetricsInterface)

WithMetrics enables metrics; it accepts MetricsInterface as metrics publisher

func (*GlobalIndex) WithPrometheusMetrics added in v0.3.0

func (gi *GlobalIndex) WithPrometheusMetrics(registry *prometheus.Registry) GlobalIndexInterface

WithPrometheusMetrics enables prometheus metrics

type GlobalIndexInterface

type GlobalIndexInterface interface {
	// WithLog enables logging; it accepts LogInterface as logger
	WithLog(log LogInterface)

	// WithMetrics enables metrics; it accepts MetricsInterface as metrics publisher
	WithMetrics(metricsInterface MetricsInterface)

	// WithPrometheusMetrics enables prometheus metrics
	WithPrometheusMetrics(registry *prometheus.Registry) GlobalIndexInterface

	// GetItemWithContext get item from index; it accepts a key interface that is used to get the table name, hash key and range key if it exists;
	// context which used to enable log with context; the output will be given in item
	// returns true if item is found, returns false and nil if no item found, returns false and an error in case of error
	GetItemWithContext(ctx context.Context, key KeyInterface, item interface{}) (bool, error)

	// GetItemsWithContext by key from index; it accepts a key interface that is used to get the table name, hash key and range key if it exists;
	// context which used to enable log with context, the output will be given in items
	// returns true if items are found, returns false and nil if no items found, returns false and error in case of error
	GetItemsWithContext(ctx context.Context, key KeyInterface, items interface{}) (bool, error)

	// GetItemsWithRangeWithContext same as GetItemsWithContext, but also respects range key
	GetItemsWithRangeWithContext(ctx context.Context, key KeyInterface, items interface{}) (bool, error)

	// QueryWithContext by query; it accepts a query interface that is used to get the table name, hash key and range key with its operator if it exists;
	// context which used to enable log with context, the output will be given in items
	// returns error in case of error
	QueryWithContext(ctx context.Context, query QueryInterface, item interface{}) error
}

type Iterator

type Iterator struct {
	// contains filtered or unexported fields
}

Iterator ...

func (*Iterator) NextItem

func (itr *Iterator) NextItem(out interface{}) bool

NextItem unmarshals the next item into out and returns if there are more items following

type IteratorInterface

type IteratorInterface interface {
	NextItem(out interface{}) bool
}

IteratorInterface ...

type KeyInterface

type KeyInterface interface {
	// TableName returns the djoemo table name
	TableName() string
	// HashKeyName returns the name of hash key if exists
	HashKeyName() *string
	// RangeKeyName returns the name of range key if exists
	RangeKeyName() *string
	// HashKey returns the hash key value
	HashKey() any
	// HashKey returns the range key value
	RangeKey() any
}

Key provides an interface for djoemo key used to identify item in djoemo table

type LogInterface

type LogInterface interface {
	// WithContext adds context to logger
	WithContext(ctx context.Context) LogInterface
	// WithField adds fields from map string interface to logger
	WithField(key string, value any) LogInterface
	// WithFields adds fields from map string interface to logger
	WithFields(fields map[string]any) LogInterface
	// Info logs info
	Info(message string)
	// warn logs warning
	Warn(message string)
	// error logs error
	Error(message string)
}

LogInterface provides an interface for logging

func NewNopLog added in v0.3.0

func NewNopLog() LogInterface

type Metrics added in v0.3.0

type Metrics struct {
	// contains filtered or unexported fields
}

func New added in v0.3.0

func New() *Metrics

func (*Metrics) Add added in v0.3.0

func (m *Metrics) Add(metric MetricsInterface)

func (*Metrics) Record added in v0.3.0

func (m *Metrics) Record(ctx context.Context, op string, key KeyInterface, duration time.Duration, success bool)

func (*Metrics) RecordMultiple added in v0.3.0

func (m *Metrics) RecordMultiple(ctx context.Context, op string, key []KeyInterface, duration time.Duration, success bool)

type MetricsInterface

type MetricsInterface interface {
	Record(ctx context.Context, caller string, key KeyInterface, duration time.Duration, success bool)
}

MetricsInterface provides an interface for metrics publisher

type Model

type Model struct {
	Version   uint
	CreatedAt *DjoemoTime
	UpdatedAt *DjoemoTime
}

Model ...

func (*Model) GetVersion

func (m *Model) GetVersion() uint

GetVersion returns the current version of the item from dynamo

func (*Model) IncreaseVersion

func (m *Model) IncreaseVersion()

IncreaseVersion increases the current version by 1

func (*Model) InitCreatedAt

func (m *Model) InitCreatedAt()

InitCreatedAt sets the CreatedAt field of the item if it hasnt been set

func (*Model) InitUpdatedAt

func (m *Model) InitUpdatedAt()

InitUpdatedAt sets the UpdatedAt

type ModelInterface

type ModelInterface interface {
	GetVersion() uint
	IncreaseVersion()
	InitCreatedAt()
	InitUpdatedAt()
}

ModelInterface ...

type Operator

type Operator string

Operator is an operation to apply comparisons.

type QueryInterface

type QueryInterface interface {
	KeyInterface
	RangeOp() Operator
	Limit() *int64
	Descending() bool
}

QueryInterface provides an interface for djoemo query used to query item in djoemo table

type Repository

type Repository struct {
	// contains filtered or unexported fields
}

Repository facade for github.com/guregu/djoemo

func (Repository) BatchGetItemsWithContext added in v0.2.0

func (repository Repository) BatchGetItemsWithContext(ctx context.Context, keys []KeyInterface, out interface{}) (bool, error)

BatchGetItemsWithContext gets multiple items by their keys; all keys must refer to the same table. out must be a pointer to a slice of your model type. Returns (true, nil) if at least one item is found, (false, nil) if none found, or (false, err) on error.

func (Repository) ConditionalUpdateWithContext

func (repository Repository) ConditionalUpdateWithContext(ctx context.Context, key KeyInterface, item interface{}, expression string, expressionArgs ...interface{}) (bool, error)

ConditionalUpdateWithContext updates an item when the condition is met, otherwise the update will be rejected

func (Repository) ConditionalUpdateWithUpdateExpressionsAndReturnValue

func (repository Repository) ConditionalUpdateWithUpdateExpressionsAndReturnValue(
	ctx context.Context,
	key KeyInterface,
	item interface{},
	updateExpressions UpdateExpressions,
	conditionExpression string,
	conditionArgs ...interface{},
) (bool, error)

ConditionalUpdateWithUpdateExpressionsAndReturnValue updates an item with update expressions and a condition. If the condition is met, the item will be updated and returned as it appears after the update. The first key of the updateMap specifies the Update expression to use for the expressions in the map

func (Repository) DeleteItemWithContext

func (repository Repository) DeleteItemWithContext(ctx context.Context, key KeyInterface) error

DeleteItemWithContext item by its key; it accepts key of item to be deleted; context which used to enable log with context returns error in case of error

func (Repository) DeleteItemsWithContext

func (repository Repository) DeleteItemsWithContext(ctx context.Context, keys []KeyInterface) error

DeleteItemsWithContext deletes items matching the keys; it accepts array of keys to be deleted; context which used to enable log with context returns error in case of error

func (*Repository) GIndex

func (repository *Repository) GIndex(name string) GlobalIndexInterface

GIndex creates an index repository by name

func (Repository) GetItemWithContext

func (repository Repository) GetItemWithContext(ctx context.Context, key KeyInterface, item interface{}) (bool, error)

GetItemWithContext get item; it accepts a key interface that is used to get the table name, hash key and range key if it exists; context which used to enable log with context; the output will be given in item returns true if item is found, returns false and nil if no item found, returns false and an error in case of error

func (Repository) GetItemsWithContext

func (repository Repository) GetItemsWithContext(ctx context.Context, key KeyInterface, items interface{}) (bool, error)

GetItemsWithContext by key; it accepts a key interface that is used to get the table name, hash key and range key if it exists; context which used to enable log with context, the output will be given in items returns true if items are found, returns false and nil if no items found, returns false and error in case of error

func (Repository) OptimisticLockSaveWithContext

func (repository Repository) OptimisticLockSaveWithContext(ctx context.Context, key KeyInterface, item interface{}) (bool, error)

OptimisticLockSaveWithContext saves an item if the version attribute on the server matches the version of the object

func (Repository) QueryWithContext

func (repository Repository) QueryWithContext(ctx context.Context, query QueryInterface, item interface{}) (err error)

QueryWithContext by query; it accepts a query interface that is used to get the table name, hash key and range key with its operator if it exists; context which used to enable log with context, the output will be given in items returns error in case of error

func (Repository) SaveItemWithContext

func (repository Repository) SaveItemWithContext(ctx context.Context, key KeyInterface, item interface{}) error

SaveItemWithContext it accepts a key interface, that is used to get the table name; item is the item to be saved; context which used to enable log with context returns error in case of error

func (Repository) SaveItemsWithContext

func (repository Repository) SaveItemsWithContext(ctx context.Context, key KeyInterface, items interface{}) error

SaveItemsWithContext batch save a slice of items by key; it accepts key of item to be saved; item to be saved; context which used to enable log with context returns error in case of error

func (*Repository) ScanIteratorWithContext

func (repository *Repository) ScanIteratorWithContext(ctx context.Context, key KeyInterface, searchLimit int64) (IteratorInterface, error)

ScanIteratorWithContext returns an instance of an Iterator that provides methods for scanning tables

func (Repository) UpdateWithContext

func (repository Repository) UpdateWithContext(ctx context.Context, expression UpdateExpression, key KeyInterface, values map[string]interface{}) error

UpdateWithContext updates item by key; it accepts an expression (Set, SetSet, SetIfNotExists, SetExpr); key is the key to be updated; values contains the values that should be used in the update; context which used to enable log with context returns error in case of error

func (Repository) UpdateWithUpdateExpressions

func (repository Repository) UpdateWithUpdateExpressions(
	ctx context.Context,
	key KeyInterface,
	updateExpressions UpdateExpressions,
) error

UpdateWithUpdateExpressions updates an item with update expressions defined at field level, enabling you to set different update expressions for each field. The first key of the updateMap specifies the Update expression to use for the expressions in the map

func (Repository) UpdateWithUpdateExpressionsAndReturnValue

func (repository Repository) UpdateWithUpdateExpressionsAndReturnValue(
	ctx context.Context,
	key KeyInterface,
	item interface{},
	updateExpressions UpdateExpressions,
) error

UpdateWithUpdateExpressionsAndReturnValue updates an item with update expressions defined at field level and returns the item, as it appears after the update, enabling you to set different update expressions for each field. The first key of the updateMap specifies the Update expression to use for the expressions in the map

func (*Repository) WithLog

func (repository *Repository) WithLog(log LogInterface)

WithLog enables logging; it accepts LogInterface as logger

func (*Repository) WithMetrics

func (repository *Repository) WithMetrics(metricsInterface MetricsInterface)

WithMetrics enables metrics; it accepts MetricsInterface as metrics publisher

func (*Repository) WithPrometheusMetrics added in v0.3.0

func (repository *Repository) WithPrometheusMetrics(registry *prometheus.Registry) RepositoryInterface

WithPrometheusMetrics enables prometheus metrics

type RepositoryInterface

type RepositoryInterface interface {
	// WithLog enables logging; it accepts LogInterface as logger
	WithLog(log LogInterface)

	// WithMetrics enables metrics; it accepts MetricsInterface as metrics publisher
	WithMetrics(metricsInterface MetricsInterface)

	// WithPrometheusMetrics enables prometheus metrics
	WithPrometheusMetrics(registry *prometheus.Registry) RepositoryInterface

	// GetItemWithContext get item; it accepts a key interface that is used to get the table name, hash key and range key if it exists; the output will be given in item
	// returns true if item is found, returns false and nil if no item found, returns false and an error in case of error
	GetItemWithContext(ctx context.Context, key KeyInterface, item any) (bool, error)

	// SaveItemWithContext it accepts a key interface, that is used to get the table name; item is the item to be saved; context which used to enable log with context
	// returns error in case of error
	SaveItemWithContext(ctx context.Context, key KeyInterface, item any) error

	// UpdateWithContext updates item by key; it accepts an expression (Set, SetSet, SetIfNotExists, SetExpr); key is the key to be updated;
	// values contains the values that should be used in the update; context which used to enable log with context
	// returns error in case of error
	UpdateWithContext(ctx context.Context, expression UpdateExpression, key KeyInterface, values map[string]any) error

	// UpdateWithUpdateExpressions updates an item with update expressions defined at field level, enabling you to set
	// different update expressions for each field. The first key of the updateMap specifies the Update expression to use
	// for the expressions in the map
	UpdateWithUpdateExpressions(ctx context.Context, key KeyInterface, updateExpressions UpdateExpressions) error

	// UpdateWithUpdateExpressionsAndReturnValue updates an item with update expressions defined at field level and returns
	// the item, as it appears after the update, enabling you to set different update expressions for each field. The first
	// key of the updateMap specifies the Update expression to use for the expressions in the map
	UpdateWithUpdateExpressionsAndReturnValue(ctx context.Context, key KeyInterface, item any, updateExpressions UpdateExpressions) error

	// ConditionalUpdateWithUpdateExpressionsAndReturnValue updates an item with update expressions and a condition.
	// If the condition is met, the item will be updated and returned as it appears after the update.
	// The first key of the updateMap specifies the Update expression to use for the expressions in the map
	ConditionalUpdateWithUpdateExpressionsAndReturnValue(ctx context.Context, key KeyInterface, item any, updateExpressions UpdateExpressions, conditionExpression string, conditionArgs ...any) (conditionMet bool, err error)

	// DeleteItemWithContext item by its key; it accepts key of item to be deleted; context which used to enable log with context
	// returns error in case of error
	DeleteItemWithContext(ctx context.Context, key KeyInterface) error

	// SaveItemsWithContext batch save a slice of items by key; it accepts key of item to be saved; item to be saved; context which used to enable log with context
	// returns error in case of error
	SaveItemsWithContext(ctx context.Context, key KeyInterface, items any) error

	// DeleteItemsWithContext deletes items matching the keys; it accepts array of keys to be deleted; context which used to enable log with context
	// returns error in case of error
	DeleteItemsWithContext(ctx context.Context, key []KeyInterface) error

	// GetItemsWithContext by key; it accepts key of item to get it; context which used to enable log with context
	// returns true if items are found, returns false and nil if no items found, returns false and error in case of error
	GetItemsWithContext(ctx context.Context, key KeyInterface, out any) (bool, error)

	// QueryWithContext by query; it accepts a query interface that is used to get the table name, hash key and range key with its operator if it exists;
	// context which used to enable log with context, the output will be given in items
	// returns error in case of error
	QueryWithContext(ctx context.Context, query QueryInterface, item any) error

	// GIndex returns index repository
	GIndex(name string) GlobalIndexInterface

	// OptimisticLockSaveWithContext saves an item if the version attribute on the server matches the version of the object
	OptimisticLockSaveWithContext(ctx context.Context, key KeyInterface, item any) (bool, error)

	// ScanIteratorWithContext returns an instance of an iterator that provides methods to use for scanning tables
	ScanIteratorWithContext(ctx context.Context, key KeyInterface, searchLimit int64) (IteratorInterface, error)

	// ConditionalUpdateWithContext updates an item if the passed expression and condition evaluates to true
	ConditionalUpdateWithContext(ctx context.Context, key KeyInterface, item any, expression string, expressionArgs ...any) (bool, error)

	// BatchGetItemsWithContext gets multiple items by their keys; it accepts a slice of keys (all from the same table)
	// and fills out (pointer to a slice) with any found items.
	// returns true if at least one item is found, returns false and nil if no items found, returns false and error in case of error
	BatchGetItemsWithContext(ctx context.Context, keys []KeyInterface, out any) (bool, error)
}

RepositoryInterface provides an interface to enable mocking the AWS dynamodb repository for testing your code.

func NewRepository

func NewRepository(dynamoClient dynamodbiface.DynamoDBAPI) RepositoryInterface

NewRepository factory method for djoemo repository

type UpdateExpression

type UpdateExpression string
const Add UpdateExpression = "ADD"

Add increments the path value in case of a number, or in case of a set it appends to that set. If a prior value doesn't exist it will set the path to that value.

const Set UpdateExpression = "Set"

Set changes path to the given value.

const SetExpr UpdateExpression = "SetExpr"

SetExpr performs a custom set expression, substituting the args into expr as in filter expressions.

const SetIfNotExists UpdateExpression = "SetIfNotExists"

SetIfNotExists changes path to the given value, if it does not already exist.

const SetSet UpdateExpression = "SetSet"

SetSet changes a set at the given path to the given value.

type UpdateExpressions

type UpdateExpressions map[UpdateExpression]map[string]interface{}

UpdateExpressions is a type alias used for specifiyng multiple update expressions at once

Directories

Path Synopsis
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL