feat(webhooks): align account payloads
This commit is contained in:
@@ -1,10 +1,14 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
"github.com/gochat/gochat/pkg/response"
|
||||
)
|
||||
@@ -35,7 +39,7 @@ func (h *WebhookSubscriptionHandler) List(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"webhook_subscriptions": subscriptions})
|
||||
c.JSON(http.StatusOK, gin.H{"payload": gin.H{"webhooks": serializeWebhookSubscriptions(subscriptions)}})
|
||||
}
|
||||
|
||||
// Get returns a single webhook subscription by ID.
|
||||
@@ -45,19 +49,20 @@ func (h *WebhookSubscriptionHandler) Get(c *gin.Context) {
|
||||
response.AbortWithStatusError(c, http.StatusServiceUnavailable, response.ErrInternal, "Webhook subscription service not available")
|
||||
return
|
||||
}
|
||||
accountID := getAccountID(c)
|
||||
webhookID, err := parseUintParam(c, "webhook_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid webhook id")
|
||||
return
|
||||
}
|
||||
|
||||
subscription, svcErr := h.webhookSubscriptionService.GetSubscription(c.Request.Context(), webhookID)
|
||||
subscription, svcErr := h.webhookSubscriptionService.GetWebhook(c.Request.Context(), accountID, webhookID)
|
||||
if svcErr != nil {
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "Failed to fetch webhook subscription")
|
||||
abortWebhookSubscriptionError(c, svcErr)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"webhook_subscription": subscription})
|
||||
c.JSON(http.StatusOK, gin.H{"payload": gin.H{"webhook": serializeWebhookSubscription(*subscription)}})
|
||||
}
|
||||
|
||||
// Create adds a new webhook subscription for an account.
|
||||
@@ -69,22 +74,19 @@ func (h *WebhookSubscriptionHandler) Create(c *gin.Context) {
|
||||
}
|
||||
accountID := getAccountID(c)
|
||||
|
||||
var req struct {
|
||||
URL string `json:"url" binding:"required"`
|
||||
Events []string `json:"events" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "Invalid request: url and events are required")
|
||||
var req service.WebhookSubscriptionMutation
|
||||
if err := bindJSONWrappedOrRaw(c, "webhook", &req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "Invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
subscription, err := h.webhookSubscriptionService.CreateSubscription(c.Request.Context(), accountID, req.URL, req.Events)
|
||||
subscription, err := h.webhookSubscriptionService.CreateWebhook(c.Request.Context(), accountID, req)
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "Failed to create webhook subscription")
|
||||
abortWebhookSubscriptionError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.Created(c, subscription)
|
||||
c.JSON(http.StatusOK, gin.H{"payload": gin.H{"webhook": serializeWebhookSubscription(*subscription)}})
|
||||
}
|
||||
|
||||
// Update modifies a webhook subscription.
|
||||
@@ -94,29 +96,26 @@ func (h *WebhookSubscriptionHandler) Update(c *gin.Context) {
|
||||
response.AbortWithStatusError(c, http.StatusServiceUnavailable, response.ErrInternal, "Webhook subscription service not available")
|
||||
return
|
||||
}
|
||||
id, err := parseUintParam(c, "id")
|
||||
accountID := getAccountID(c)
|
||||
id, err := parseUintAnyParam(c, "webhook_id", "id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "Invalid webhook subscription ID")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
URL string `json:"url"`
|
||||
Events []string `json:"events"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
var req service.WebhookSubscriptionMutation
|
||||
if err := bindJSONWrappedOrRaw(c, "webhook", &req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "Invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
subscription, err := h.webhookSubscriptionService.UpdateSubscription(c.Request.Context(), id, req.URL, req.Events, req.Active)
|
||||
subscription, err := h.webhookSubscriptionService.UpdateWebhook(c.Request.Context(), accountID, id, req)
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "Failed to update webhook subscription")
|
||||
abortWebhookSubscriptionError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, subscription)
|
||||
c.JSON(http.StatusOK, gin.H{"payload": gin.H{"webhook": serializeWebhookSubscription(*subscription)}})
|
||||
}
|
||||
|
||||
// Delete removes a webhook subscription.
|
||||
@@ -126,18 +125,19 @@ func (h *WebhookSubscriptionHandler) Delete(c *gin.Context) {
|
||||
response.AbortWithStatusError(c, http.StatusServiceUnavailable, response.ErrInternal, "Webhook subscription service not available")
|
||||
return
|
||||
}
|
||||
id, err := parseUintParam(c, "id")
|
||||
accountID := getAccountID(c)
|
||||
id, err := parseUintAnyParam(c, "webhook_id", "id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "Invalid webhook subscription ID")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.webhookSubscriptionService.DeleteSubscription(c.Request.Context(), id); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "Failed to delete webhook subscription")
|
||||
if err := h.webhookSubscriptionService.DeleteWebhook(c.Request.Context(), accountID, id); err != nil {
|
||||
abortWebhookSubscriptionError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.NoContent(c)
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
// ListDeliveries returns recent webhook delivery records for a subscription.
|
||||
@@ -160,4 +160,41 @@ func (h *WebhookSubscriptionHandler) ListDeliveries(c *gin.Context) {
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"deliveries": deliveries})
|
||||
}
|
||||
}
|
||||
|
||||
func abortWebhookSubscriptionError(c *gin.Context, err error) {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "webhook not found")
|
||||
return
|
||||
}
|
||||
response.AbortWithStatusError(c, http.StatusUnprocessableEntity, response.ErrValidation, err.Error())
|
||||
}
|
||||
|
||||
func serializeWebhookSubscriptions(subscriptions []model.WebhookSubscription) []gin.H {
|
||||
items := make([]gin.H, 0, len(subscriptions))
|
||||
for _, subscription := range subscriptions {
|
||||
items = append(items, serializeWebhookSubscription(subscription))
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func serializeWebhookSubscription(subscription model.WebhookSubscription) gin.H {
|
||||
var subscriptions []string
|
||||
_ = json.Unmarshal(subscription.Events, &subscriptions)
|
||||
payload := gin.H{
|
||||
"id": subscription.ID,
|
||||
"name": subscription.Name,
|
||||
"url": subscription.URL,
|
||||
"account_id": subscription.AccountID,
|
||||
"subscriptions": subscriptions,
|
||||
"secret": subscription.Secret,
|
||||
}
|
||||
if subscription.InboxID != nil && *subscription.InboxID != 0 {
|
||||
inbox := gin.H{"id": *subscription.InboxID}
|
||||
if subscription.Inbox.ID != 0 {
|
||||
inbox["name"] = subscription.Inbox.Name
|
||||
}
|
||||
payload["inbox"] = inbox
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package v1
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -31,7 +33,7 @@ func (s *WebhookSubscriptionHandlerTestSuite) SetupSuite() {
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
s.Require().NoError(db.AutoMigrate(&model.Account{}, &model.WebhookSubscription{}))
|
||||
s.Require().NoError(db.AutoMigrate(&model.Account{}, &model.Inbox{}, &model.WebhookSubscription{}))
|
||||
s.db = db
|
||||
|
||||
repo := repository.NewWebhookSubscriptionRepo(db)
|
||||
@@ -55,21 +57,98 @@ func TestWebhookSubscriptionHandlerSuite(t *testing.T) {
|
||||
|
||||
func (s *WebhookSubscriptionHandlerTestSuite) TestList_Success() {
|
||||
r := gin.New()
|
||||
r.GET("/api/v1/accounts/:account_id/webhooks/:webhook_id/subscriptions", s.handler.List)
|
||||
r.GET("/api/v1/accounts/:account_id/webhooks", s.handler.List)
|
||||
|
||||
_, err := s.handler.webhookSubscriptionService.CreateWebhook(context.Background(), s.account.ID, service.WebhookSubscriptionMutation{
|
||||
Name: "List hook",
|
||||
URL: "https://example.com/list-hook",
|
||||
Subscriptions: []string{"message_created"},
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/webhooks/1/subscriptions", s.account.ID), nil)
|
||||
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/webhooks", s.account.ID), nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(s.T(), http.StatusOK, w.Code)
|
||||
var body map[string]any
|
||||
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &body))
|
||||
payload := body["payload"].(map[string]any)
|
||||
webhooks := payload["webhooks"].([]any)
|
||||
s.NotEmpty(webhooks)
|
||||
}
|
||||
|
||||
func (s *WebhookSubscriptionHandlerTestSuite) TestCreate_Success_ChatwootPayload() {
|
||||
r := gin.New()
|
||||
r.POST("/api/v1/accounts/:account_id/webhooks", s.handler.Create)
|
||||
|
||||
body := `{"webhook":{"name":"Created hook","url":"https://example.com/created-hook","subscriptions":["conversation_created","message_created"]}}`
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/webhooks", s.account.ID), bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(s.T(), http.StatusOK, w.Code)
|
||||
var parsed map[string]any
|
||||
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &parsed))
|
||||
webhook := parsed["payload"].(map[string]any)["webhook"].(map[string]any)
|
||||
s.Equal("Created hook", webhook["name"])
|
||||
s.Equal("https://example.com/created-hook", webhook["url"])
|
||||
s.NotEmpty(webhook["secret"])
|
||||
s.Equal([]any{"conversation_created", "message_created"}, webhook["subscriptions"])
|
||||
}
|
||||
|
||||
func (s *WebhookSubscriptionHandlerTestSuite) TestUpdate_Success_ChatwootPayload() {
|
||||
created, err := s.handler.webhookSubscriptionService.CreateWebhook(context.Background(), s.account.ID, service.WebhookSubscriptionMutation{
|
||||
Name: "Before",
|
||||
URL: "https://example.com/update-before",
|
||||
Subscriptions: []string{"message_created"},
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
r := gin.New()
|
||||
r.PATCH("/api/v1/accounts/:account_id/webhooks/:webhook_id", s.handler.Update)
|
||||
|
||||
body := `{"webhook":{"name":"After","url":"https://example.com/update-after","subscriptions":["contact_created"]}}`
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/webhooks/%d", s.account.ID, created.ID), bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(s.T(), http.StatusOK, w.Code)
|
||||
var parsed map[string]any
|
||||
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &parsed))
|
||||
webhook := parsed["payload"].(map[string]any)["webhook"].(map[string]any)
|
||||
s.Equal("After", webhook["name"])
|
||||
s.Equal("https://example.com/update-after", webhook["url"])
|
||||
s.Equal([]any{"contact_created"}, webhook["subscriptions"])
|
||||
}
|
||||
|
||||
func (s *WebhookSubscriptionHandlerTestSuite) TestDelete_Success_ReturnsEmptyOK() {
|
||||
created, err := s.handler.webhookSubscriptionService.CreateWebhook(context.Background(), s.account.ID, service.WebhookSubscriptionMutation{
|
||||
Name: "Delete",
|
||||
URL: "https://example.com/delete-hook",
|
||||
Subscriptions: []string{"message_created"},
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
r := gin.New()
|
||||
r.DELETE("/api/v1/accounts/:account_id/webhooks/:webhook_id", s.handler.Delete)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/webhooks/%d", s.account.ID, created.ID), nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(s.T(), http.StatusOK, w.Code)
|
||||
s.Empty(w.Body.String())
|
||||
}
|
||||
|
||||
func (s *WebhookSubscriptionHandlerTestSuite) TestCreate_BadRequest_EmptyBody() {
|
||||
r := gin.New()
|
||||
r.POST("/api/v1/accounts/:account_id/webhooks/:webhook_id/subscriptions", s.handler.Create)
|
||||
r.POST("/api/v1/accounts/:account_id/webhooks", s.handler.Create)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/webhooks/1/subscriptions", s.account.ID), nil)
|
||||
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/webhooks", s.account.ID), nil)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
@@ -78,22 +157,21 @@ func (s *WebhookSubscriptionHandlerTestSuite) TestCreate_BadRequest_EmptyBody()
|
||||
|
||||
func (s *WebhookSubscriptionHandlerTestSuite) TestGet_BadRequest_InvalidID() {
|
||||
r := gin.New()
|
||||
r.GET("/api/v1/accounts/:account_id/webhooks/:webhook_id/subscriptions/:webhook_id", s.handler.Get)
|
||||
r.GET("/api/v1/accounts/:account_id/webhooks/:webhook_id", s.handler.Get)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/webhooks/1/subscriptions/abc", s.account.ID), nil)
|
||||
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/webhooks/abc", s.account.ID), nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
// Get returns 500 for invalid id (parseUintParam error → internal server error path)
|
||||
assert.NotEqual(s.T(), http.StatusOK, w.Code)
|
||||
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
|
||||
}
|
||||
|
||||
func (s *WebhookSubscriptionHandlerTestSuite) TestUpdate_BadRequest_InvalidID() {
|
||||
r := gin.New()
|
||||
r.PUT("/api/v1/accounts/:account_id/webhooks/:webhook_id/subscriptions/:webhook_id", s.handler.Update)
|
||||
r.PATCH("/api/v1/accounts/:account_id/webhooks/:webhook_id", s.handler.Update)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/%d/webhooks/1/subscriptions/abc", s.account.ID), bytes.NewBufferString(`{"url":"https://example.com"}`))
|
||||
req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/webhooks/abc", s.account.ID), bytes.NewBufferString(`{"webhook":{"url":"https://example.com","subscriptions":["message_created"]}}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
@@ -102,10 +180,10 @@ func (s *WebhookSubscriptionHandlerTestSuite) TestUpdate_BadRequest_InvalidID()
|
||||
|
||||
func (s *WebhookSubscriptionHandlerTestSuite) TestDelete_BadRequest_InvalidID() {
|
||||
r := gin.New()
|
||||
r.DELETE("/api/v1/accounts/:account_id/webhooks/:webhook_id/subscriptions/:webhook_id", s.handler.Delete)
|
||||
r.DELETE("/api/v1/accounts/:account_id/webhooks/:webhook_id", s.handler.Delete)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/webhooks/1/subscriptions/abc", s.account.ID), nil)
|
||||
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/webhooks/abc", s.account.ID), nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
|
||||
@@ -120,4 +198,4 @@ func (s *WebhookSubscriptionHandlerTestSuite) TestListDeliveries_BadRequest_Inva
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user