add WebSocket support for real-time delivery updates with JWT authentication and automatic reconnection
Some checks failed
Build and Push Docker Images / build-backend (push) Has been cancelled
Build and Push Docker Images / build-frontend (push) Has been cancelled

This commit is contained in:
Egor Pozharov
2026-05-21 15:52:05 +06:00
parent c87aea47ce
commit d1efebbb34
16 changed files with 408 additions and 73 deletions

View File

@@ -2,10 +2,12 @@ package delivery
import (
"errors"
"log"
"net/http"
"time"
sqlc "github.com/chedius/delivery-tracker/internal/db/sqlc"
"github.com/chedius/delivery-tracker/internal/ws"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
@@ -13,6 +15,7 @@ import (
type Handler struct {
queries *sqlc.Queries
hub *ws.Hub
}
// DeliveryRequest represents the request body for creating or updating a delivery
@@ -38,8 +41,8 @@ type DeliveryRequest struct {
Comment string `json:"comment"`
}
func NewHandler(queries *sqlc.Queries) *Handler {
return &Handler{queries: queries}
func NewHandler(queries *sqlc.Queries, hub *ws.Hub) *Handler {
return &Handler{queries: queries, hub: hub}
}
// GET /api/deliveries/:id
@@ -139,6 +142,7 @@ func (h *Handler) CreateDelivery(c *gin.Context) {
return
}
h.hub.Broadcast(ws.NewEvent(ws.DeliveryCreated, res))
c.JSON(http.StatusOK, gin.H{"message": "Delivery created", "id": res.ID.String()})
}
@@ -199,6 +203,11 @@ func (h *Handler) UpdateDelivery(c *gin.Context) {
return
}
if updated, err := h.queries.GetDeliveryByID(c.Request.Context(), pgtype.UUID{Bytes: parsedID, Valid: true}); err == nil {
h.hub.Broadcast(ws.NewEvent(ws.DeliveryUpdated, updated))
} else {
log.Printf("delivery: failed to fetch updated delivery %s for ws broadcast: %v", id, err)
}
c.JSON(http.StatusOK, gin.H{"message": "Delivery updated"})
}
@@ -240,6 +249,7 @@ func (h *Handler) UpdateDeliveryStatus(c *gin.Context) {
return
}
h.hub.Broadcast(ws.NewEvent(ws.DeliveryStatusChanged, ws.StatusPayload{ID: id, Status: status}))
c.JSON(http.StatusOK, gin.H{"message": "Delivery status updated"})
}
@@ -263,6 +273,7 @@ func (h *Handler) DeleteDelivery(c *gin.Context) {
return
}
h.hub.Broadcast(ws.NewEvent(ws.DeliveryDeleted, ws.DeletePayload{ID: id}))
c.JSON(http.StatusOK, gin.H{"message": "Delivery deleted"})
}