feat(notifications): align subscription payloads
This commit is contained in:
@@ -1,9 +1,12 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
)
|
||||
|
||||
@@ -22,14 +25,14 @@ func NewNotificationSubscriptionHandler(svc *service.NotificationSubscriptionSer
|
||||
// POST /api/v1/notification_subscriptions
|
||||
// Chatwoot: requires identifier, subscription_attributes, subscription_type
|
||||
func (h *NotificationSubscriptionHandler) Create(c *gin.Context) {
|
||||
userID, exists := c.Get("current_user_id")
|
||||
if !exists {
|
||||
userID := getUserID(c)
|
||||
if userID == 0 {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
var req service.CreateSubscriptionRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := bindJSONWrappedOrRaw(c, "notification_subscription", &req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
@@ -40,35 +43,62 @@ func (h *NotificationSubscriptionHandler) Create(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
sub, err := h.svc.Create(c.Request.Context(), userID.(uint), &req)
|
||||
sub, err := h.svc.Create(c.Request.Context(), userID, &req)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, sub)
|
||||
c.JSON(http.StatusOK, notificationSubscriptionPayloadFromModel(sub))
|
||||
}
|
||||
|
||||
// Destroy removes a notification subscription.
|
||||
// DELETE /api/v1/notification_subscriptions/:identifier
|
||||
// Chatwoot: finds by identifier and deletes
|
||||
func (h *NotificationSubscriptionHandler) Destroy(c *gin.Context) {
|
||||
userID, exists := c.Get("current_user_id")
|
||||
if !exists {
|
||||
userID := getUserID(c)
|
||||
if userID == 0 {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
identifier := c.Param("identifier")
|
||||
if identifier == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "identifier is required"})
|
||||
return
|
||||
pushToken := c.Query("push_token")
|
||||
if pushToken == "" {
|
||||
pushToken = c.Param("identifier")
|
||||
}
|
||||
if pushToken == "" {
|
||||
pushToken = c.PostForm("push_token")
|
||||
}
|
||||
if pushToken == "" && c.Request.Body != nil {
|
||||
var body struct {
|
||||
PushToken string `json:"push_token"`
|
||||
}
|
||||
_ = c.ShouldBindJSON(&body)
|
||||
pushToken = body.PushToken
|
||||
}
|
||||
|
||||
if err := h.svc.Destroy(c.Request.Context(), userID.(uint), identifier); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
_ = h.svc.Destroy(c.Request.Context(), userID, pushToken)
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{})
|
||||
}
|
||||
type notificationSubscriptionDTO struct {
|
||||
ID uint `json:"id"`
|
||||
Identifier string `json:"identifier"`
|
||||
SubscriptionAttributes json.RawMessage `json:"subscription_attributes"`
|
||||
SubscriptionType string `json:"subscription_type"`
|
||||
UserID uint `json:"user_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func notificationSubscriptionPayloadFromModel(sub *model.NotificationSubscription) notificationSubscriptionDTO {
|
||||
return notificationSubscriptionDTO{
|
||||
ID: sub.ID,
|
||||
Identifier: sub.Identifier,
|
||||
SubscriptionAttributes: sub.SubscriptionAttributes,
|
||||
SubscriptionType: sub.SubscriptionType.String(),
|
||||
UserID: sub.UserID,
|
||||
CreatedAt: sub.CreatedAt,
|
||||
UpdatedAt: sub.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func setupNotificationSubscriptionHandlerTest(t *testing.T, userID uint) (*gin.Engine, *gorm.DB) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&model.User{}, &model.NotificationSubscription{}))
|
||||
|
||||
handler := NewNotificationSubscriptionHandler(service.NewNotificationSubscriptionService(repository.NewNotificationSubscriptionRepo(db)))
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) {
|
||||
c.Set("user_id", userID)
|
||||
c.Next()
|
||||
})
|
||||
router.POST("/api/v1/notification_subscriptions", handler.Create)
|
||||
router.DELETE("/api/v1/notification_subscriptions", handler.Destroy)
|
||||
router.DELETE("/api/v1/notification_subscriptions/:identifier", handler.Destroy)
|
||||
return router, db
|
||||
}
|
||||
|
||||
func TestNotificationSubscriptionCreateAcceptsFrontendPayload(t *testing.T) {
|
||||
router, db := setupNotificationSubscriptionHandlerTest(t, 7)
|
||||
body := `{"subscription_type":"browser_push","subscription_attributes":{"endpoint":"https://push.example/sub","p256dh":"key","auth":"secret"}}`
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/notification_subscriptions", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
var payload map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload), w.Body.String())
|
||||
require.NotContains(t, payload, "success")
|
||||
require.NotContains(t, payload, "data")
|
||||
require.Equal(t, "https://push.example/sub", payload["identifier"])
|
||||
require.Equal(t, "browser_push", payload["subscription_type"])
|
||||
require.Equal(t, float64(7), payload["user_id"])
|
||||
|
||||
var sub model.NotificationSubscription
|
||||
require.NoError(t, db.First(&sub).Error)
|
||||
require.Equal(t, uint(7), sub.UserID)
|
||||
require.Equal(t, "https://push.example/sub", sub.Identifier)
|
||||
}
|
||||
|
||||
func TestNotificationSubscriptionCreateAcceptsRailsWrapperAndUpdatesExisting(t *testing.T) {
|
||||
router, db := setupNotificationSubscriptionHandlerTest(t, 11)
|
||||
existing := model.NotificationSubscription{
|
||||
Identifier: "device-1",
|
||||
UserID: 2,
|
||||
SubscriptionType: model.NotificationSubFCM,
|
||||
SubscriptionAttributes: json.RawMessage(`{"device_id":"device-1","push_token":"old"}`),
|
||||
}
|
||||
require.NoError(t, db.Create(&existing).Error)
|
||||
body := `{"notification_subscription":{"subscription_type":"fcm","subscription_attributes":{"device_id":"device-1","push_token":"new"}}}`
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/notification_subscriptions", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
var sub model.NotificationSubscription
|
||||
require.NoError(t, db.First(&sub, existing.ID).Error)
|
||||
require.Equal(t, uint(11), sub.UserID)
|
||||
require.JSONEq(t, `{"device_id":"device-1","push_token":"new"}`, string(sub.SubscriptionAttributes))
|
||||
}
|
||||
|
||||
func TestNotificationSubscriptionDestroyUsesPushTokenAndReturnsEmptyOK(t *testing.T) {
|
||||
router, db := setupNotificationSubscriptionHandlerTest(t, 7)
|
||||
sub := model.NotificationSubscription{
|
||||
Identifier: "https://push.example/sub",
|
||||
UserID: 7,
|
||||
SubscriptionType: model.NotificationSubBrowserPush,
|
||||
SubscriptionAttributes: json.RawMessage(`{"endpoint":"https://push.example/sub","p256dh":"key","auth":"secret"}`),
|
||||
}
|
||||
require.NoError(t, db.Create(&sub).Error)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/notification_subscriptions?push_token=https%3A%2F%2Fpush.example%2Fsub", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
require.Empty(t, w.Body.String())
|
||||
var count int64
|
||||
require.NoError(t, db.Model(&model.NotificationSubscription{}).Where("id = ?", sub.ID).Count(&count).Error)
|
||||
require.Equal(t, int64(0), count)
|
||||
}
|
||||
|
||||
func TestNotificationSubscriptionDestroyMissingTokenStillOK(t *testing.T) {
|
||||
router, _ := setupNotificationSubscriptionHandlerTest(t, 7)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/notification_subscriptions", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
require.Empty(t, w.Body.String())
|
||||
}
|
||||
Reference in New Issue
Block a user