impl webhooks.Record(), .Did()

main
Bel LaPointe 2025-04-28 20:39:42 -06:00
parent 83026a67d4
commit 5ed296a3d2
2 changed files with 89 additions and 0 deletions

55
src/webhooks/db.go Normal file
View File

@ -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 ''`,
})
}

34
src/webhooks/db_test.go Normal file
View File

@ -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)
}
}