Files
Messenger/server/internal/store/push.go
T

62 lines
1.8 KiB
Go
Raw Normal View History

package store
import (
"context"
"time"
)
// PushSubscription is a browser Web Push endpoint registered by a user.
type PushSubscription struct {
ID int64
UserID int64
Endpoint string
P256dh string
Auth string
CreatedAt time.Time
}
// CreatePushSubscription stores a subscription, replacing any previous one
// bound to the same endpoint.
func (s *Store) CreatePushSubscription(ctx context.Context, sub PushSubscription) (*PushSubscription, error) {
err := s.pool.QueryRow(ctx, `
INSERT INTO push_subscriptions(user_id, endpoint, p256dh, auth)
VALUES($1, $2, $3, $4)
ON CONFLICT (endpoint) DO UPDATE SET user_id = EXCLUDED.user_id, p256dh = EXCLUDED.p256dh, auth = EXCLUDED.auth
RETURNING id, created_at
`, sub.UserID, sub.Endpoint, sub.P256dh, sub.Auth).Scan(&sub.ID, &sub.CreatedAt)
if err != nil {
return nil, err
}
return &sub, nil
}
// DeletePushSubscription removes a subscription by endpoint and owner.
func (s *Store) DeletePushSubscription(ctx context.Context, userID int64, endpoint string) error {
_, err := s.pool.Exec(ctx, `
DELETE FROM push_subscriptions WHERE user_id=$1 AND endpoint=$2
`, userID, endpoint)
return err
}
// ListPushSubscriptionsForUser returns all endpoints registered by a user.
func (s *Store) ListPushSubscriptionsForUser(ctx context.Context, userID int64) ([]PushSubscription, error) {
rows, err := s.pool.Query(ctx, `
SELECT id, user_id, endpoint, p256dh, auth, created_at
FROM push_subscriptions WHERE user_id=$1
`, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var subs []PushSubscription
for rows.Next() {
var sub PushSubscription
if err := rows.Scan(&sub.ID, &sub.UserID, &sub.Endpoint, &sub.P256dh, &sub.Auth, &sub.CreatedAt); err != nil {
return nil, err
}
subs = append(subs, sub)
}
return subs, nil
}