90 lines
1.6 KiB
Go
90 lines
1.6 KiB
Go
package raw_events
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
type (
|
|
Store struct {
|
|
db *pgxpool.Pool
|
|
}
|
|
|
|
Event struct {
|
|
Platform string
|
|
StoreID string
|
|
EventID string
|
|
EventTimestamp time.Time
|
|
Payload json.RawMessage
|
|
}
|
|
)
|
|
|
|
func NewStore(ctx context.Context) (*Store, error) {
|
|
pool, err := newPool(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &Store{
|
|
db: pool,
|
|
}, nil
|
|
}
|
|
|
|
func newPool(ctx context.Context) (*pgxpool.Pool, error) {
|
|
pool, err := pgxpool.New(ctx, "postgres://app_client:app_password@localhost:5432/inventory_2?sslmode=disable")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create database client: %w", err)
|
|
}
|
|
|
|
conn, err := pool.Acquire(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create a database connection: %w", err)
|
|
}
|
|
conn.Release()
|
|
|
|
return pool, nil
|
|
}
|
|
|
|
func (db *Store) Save(ctx context.Context, e *Event) error {
|
|
_, err := db.db.Exec(
|
|
ctx,
|
|
`
|
|
INSERT INTO raw_store_events (
|
|
platform,
|
|
store_id,
|
|
event_timestamp,
|
|
event_id,
|
|
raw_payload
|
|
)
|
|
VALUES (
|
|
@platform,
|
|
@store_id,
|
|
@event_timestamp,
|
|
@event_id,
|
|
@raw_payload
|
|
)
|
|
`,
|
|
pgx.NamedArgs{
|
|
"platform": e.Platform,
|
|
"store_id": e.StoreID,
|
|
"event_timestamp": pgtype.Timestamptz{
|
|
Time: e.EventTimestamp,
|
|
Valid: !e.EventTimestamp.IsZero(),
|
|
},
|
|
"event_id": e.EventID,
|
|
"raw_payload": string(e.Payload),
|
|
},
|
|
)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to perform query: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|