Last active
December 22, 2021 14:40
-
-
Save Jimeux/5de4cce45d808e953259ca6f925f26f5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Connection stores a reference to an active WebSocket connection. | |
type Connection struct { | |
ConnectionID string `dynamodbav:"connection_id" json:"connectionId"` | |
Username string `dynamodbav:"username,omitempty" json:"username,omitempty"` // not unique | |
} | |
// Repository implements CRUD operations on the Connection table. | |
type Repository struct { | |
ddb awsiface.DynamoDB | |
tableName *string | |
} | |
func NewRepository(ddb awsiface.DynamoDB, tableName string) *Repository { | |
return &Repository{ | |
ddb: ddb, | |
tableName: &tableName, | |
} | |
} | |
// NewRepositoryFromConfig is a convenience function for creating | |
// a Repository from an aws.Config instance. | |
func NewRepositoryFromConfig(cfg aws.Config, tableName string) *Repository { | |
ddb := dynamodb.NewFromConfig(cfg) | |
return NewRepository(ddb, tableName) | |
} | |
// SaveConnection creates or updates a Connection record with the given values. | |
func (r *Repository) SaveConnection(ctx context.Context, connID, username string) error { | |
conn := &Connection{ | |
ConnectionID: connID, | |
Username: username, | |
} | |
av, err := attributevalue.MarshalMap(conn) | |
if err != nil { | |
return fmt.Errorf("failed to marshal connection: %w", err) | |
} | |
if _, err := r.ddb.PutItem(ctx, &dynamodb.PutItemInput{ | |
Item: av, | |
TableName: r.tableName, | |
}); err != nil { | |
return fmt.Errorf("failed PutItem for connection: %w", err) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment