Skip to content

Commit

Permalink
feat: adding pg config to context
Browse files Browse the repository at this point in the history
  • Loading branch information
katallaxie authored Oct 9, 2024
1 parent 6635942 commit 0d9b7c1
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
19 changes: 19 additions & 0 deletions dbx/pg/config.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,32 @@
package pg

import (
"context"
"fmt"
"strconv"
"strings"

"github.com/zeiss/pkg/utilx"
)

type contextKey int

const (
configKey contextKey = iota
)

// Context returns a new Context that carries the provided Config.
func (cfg Config) Context(ctx context.Context) context.Context {
return context.WithValue(ctx, configKey, cfg)
}

// FromContext will return the Config carried in the provided Context.
//
// It panics if config is not available on the current context.
func FromContext(ctx context.Context) Config {
return ctx.Value(configKey).(Config)
}

// Config represents configuration for PostgreSQL connection
type Config struct {
Database string `envconfig:"PG_DB_NAME"`
Expand Down
17 changes: 17 additions & 0 deletions dbx/pg/config_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package pg_test

import (
"context"
"testing"

"github.com/zeiss/pkg/dbx/pg"
Expand Down Expand Up @@ -33,3 +34,19 @@ func TestFormatDSN(t *testing.T) {
dsn := config.FormatDSN()
assert.Equal(t, "dbname=test_db user=test_user password=password host=localhost port=5432 sslmode=disable", dsn)
}

func TestContext(t *testing.T) {
t.Parallel()

config := pg.Config{
Database: "test_db",
Host: "localhost",
Password: "password",
Port: 5432,
SslMode: "disable",
User: "test_user",
}

ctx := config.Context(context.Background())
assert.Equal(t, config, pg.FromContext(ctx))
}

0 comments on commit 0d9b7c1

Please sign in to comment.