From 5ed296a3d28b05a01a757cc7594a6eadb19bf6e5 Mon Sep 17 00:00:00 2001 From: Bel LaPointe <153096461+breel-render@users.noreply.github.com> Date: Mon, 28 Apr 2025 20:39:42 -0600 Subject: [PATCH] impl webhooks.Record(), .Did() --- src/webhooks/db.go | 55 +++++++++++++++++++++++++++++++++++++++++ src/webhooks/db_test.go | 34 +++++++++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 src/webhooks/db.go create mode 100644 src/webhooks/db_test.go diff --git a/src/webhooks/db.go b/src/webhooks/db.go new file mode 100644 index 0000000..e8cdd56 --- /dev/null +++ b/src/webhooks/db.go @@ -0,0 +1,55 @@ +package webhooks + +import ( + "context" + "show-rss/src/db" + "time" + + "github.com/google/uuid" +) + +func Did(ctx context.Context, method, url, body string) (bool, error) { + if err := initDB(ctx); err != nil { + return false, err + } + + type Did struct { + Did int + } + result, err := db.QueryOne[Did](ctx, ` + SELECT 1 AS "Did" FROM "webhook.executions" WHERE method=$1 AND url=$2 AND body=$3 + `, method, url, body) + return result.Did > 0 && err == nil, err +} + +func Record(ctx context.Context, method, url, body string) error { + if err := initDB(ctx); err != nil { + return err + } + + now := time.Now() + id := uuid.New().String() + return db.Exec(ctx, ` + INSERT INTO "webhook.executions" ( + id, + executed_at, + method, + url, + body + ) VALUES ($1, $2, $3, $4, $5) + `, + id, now, method, url, body, + ) +} + +func initDB(ctx context.Context) error { + return db.InitializeSchema(ctx, "webhooks", []string{ + `CREATE TABLE "webhook.executions" ( + id TEXT PRIMARY KEY NOT NULL, + executed_at TIMESTAMP NOT NULL + )`, + `ALTER TABLE "webhook.executions" ADD COLUMN method TEXT NOT NULL DEFAULT ''`, + `ALTER TABLE "webhook.executions" ADD COLUMN url TEXT NOT NULL DEFAULT ''`, + `ALTER TABLE "webhook.executions" ADD COLUMN body TEXT NOT NULL DEFAULT ''`, + }) +} diff --git a/src/webhooks/db_test.go b/src/webhooks/db_test.go new file mode 100644 index 0000000..21c5c38 --- /dev/null +++ b/src/webhooks/db_test.go @@ -0,0 +1,34 @@ +package webhooks_test + +import ( + "context" + "show-rss/src/db" + "show-rss/src/webhooks" + "testing" +) + +func TestWebhooks(t *testing.T) { + ctx := db.Test(t, context.Background()) + + if did, err := webhooks.Did(ctx, "m", "u", "b"); err != nil { + t.Errorf("cannot Did() empty: %v", err) + } else if did { + t.Errorf("wrong Did() empty: %v", did) + } + + if err := webhooks.Record(ctx, "m", "u", "b"); err != nil { + t.Errorf("cannot Record() empty: %v", err) + } + + if did, err := webhooks.Did(ctx, "m", "u", "b"); err != nil { + t.Errorf("cannot Did() one: %v", err) + } else if !did { + t.Errorf("wrong Did() one: %v", did) + } + + if did, err := webhooks.Did(ctx, "m2", "u", "b"); err != nil { + t.Errorf("cannot Did() wrong one: %v", err) + } else if did { + t.Errorf("wrong Did() wrong one: %v", did) + } +}