commit 0d768728d597593d9ab310191477a88b0459342e
parent 4865e3c543765cce96f2054b143ed911eca3275b
Author: Jacob R. Edwards <jacob@jacobedwards.org>
Date: Mon, 23 Sep 2024 14:12:22 -0700
Ensure subscription status is up to date on startup
I'v added a method to the backend which fetches all the subscriptions
from Stripe and updates the local database accordingly.
Diffstat:
2 files changed, 27 insertions(+), 0 deletions(-)
diff --git a/cmd/api/main.go b/cmd/api/main.go
@@ -73,6 +73,9 @@ func main() {
engine.Use(AuthMiddleware(e.Auth))
setRoutes(e, engine.Group("/v0"))
+ // Update subscriptions in another thread
+ go e.backend.StripeUpdateSubs()
+
if len(bindTo) > 0 {
engine.Run(bindTo)
} else {
diff --git a/internal/backend/stripe.go b/internal/backend/stripe.go
@@ -77,6 +77,30 @@ func (e *Env) stripeDeleteSub(s *stripe.Subscription) error {
}
+// Fetch all subscriptions anew
+func (e *Env) StripeUpdateSubs() error {
+ log.Printf("Fetching subscriptions")
+
+ tx, err := e.DB.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ subs := e.Stripe.Subscriptions.List(nil)
+ for subs.Next() {
+ err := e.stripeUpdateSub(subs.Subscription())
+ if err != nil {
+ return err
+ }
+ }
+ if err := subs.Err(); err != nil {
+ return err
+ }
+
+ return tx.Commit()
+}
+
func stripeHandle[T any](handler func(*T) error, ev *stripe.Event) error {
var d T
if err := json.Unmarshal(ev.Data.Raw, &d); err != nil {