74 lines
2.2 KiB
Go
74 lines
2.2 KiB
Go
package v1
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/gochat/gochat/internal/service"
|
|
)
|
|
|
|
// NotificationSubscriptionHandler handles notification subscription API endpoints.
|
|
// Reference: Chatwoot app/controllers/api/v1/notification_subscriptions_controller.rb
|
|
// Routes: resource :notification_subscriptions, only: [:create, :destroy]
|
|
type NotificationSubscriptionHandler struct {
|
|
svc *service.NotificationSubscriptionService
|
|
}
|
|
|
|
func NewNotificationSubscriptionHandler(svc *service.NotificationSubscriptionService) *NotificationSubscriptionHandler {
|
|
return &NotificationSubscriptionHandler{svc: svc}
|
|
}
|
|
|
|
// Create adds a new notification subscription.
|
|
// 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 {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
|
return
|
|
}
|
|
|
|
var req service.CreateSubscriptionRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
// Validate subscription_attributes based on type
|
|
if err := service.ValidateSubscriptionAttributes(req.SubscriptionType, req.SubscriptionAttributes); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
sub, err := h.svc.Create(c.Request.Context(), userID.(uint), &req)
|
|
if err != nil {
|
|
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, 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 {
|
|
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
|
|
}
|
|
|
|
if err := h.svc.Destroy(c.Request.Context(), userID.(uint), identifier); err != nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{})
|
|
} |