Skip to content

Instantly share code, notes, and snippets.

@Jimeux
Last active December 22, 2021 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jimeux/5de4cce45d808e953259ca6f925f26f5 to your computer and use it in GitHub Desktop.
Save Jimeux/5de4cce45d808e953259ca6f925f26f5 to your computer and use it in GitHub Desktop.
// 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