tsk-44: Record when message was sent (#48)
Closes #44 Reviewed-on: phoenix/textsender-api#48 Co-authored-by: phoenix <kundeng00@pm.me> Co-committed-by: phoenix <kundeng00@pm.me>
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-models/tx0/message"
|
||||
"git.kundeng.us/phoenix/textsender-models/tx0/types"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||
)
|
||||
|
||||
type EventResponseHandler struct {
|
||||
MessageEventResponseStore store.MessageEventResponseStore
|
||||
}
|
||||
|
||||
func NewEventResponseHandler(str store.MessageEventResponseStore) *EventResponseHandler {
|
||||
return &EventResponseHandler{MessageEventResponseStore: str}
|
||||
}
|
||||
|
||||
type RecordEventRequest struct {
|
||||
ScheduledMessageEventId uuid.UUID `json:"scheduled_message_event_id"`
|
||||
Response types.JSONB `json:"response"`
|
||||
UserId uuid.UUID `json:"user_id"`
|
||||
Sent *time.Time `json:"sent,omitempty"`
|
||||
}
|
||||
|
||||
type RecordEventResponse struct {
|
||||
Message string `json:"message"`
|
||||
Data []*message.MessageEventResponse `json:"data"`
|
||||
}
|
||||
|
||||
func (e *EventResponseHandler) RecordResponse(w http.ResponseWriter, r *http.Request) {
|
||||
var req RecordEventRequest
|
||||
if err := ExtractFromRequest(r, &req); err != nil {
|
||||
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
var statusCode int
|
||||
var rp message.MessageEventResponse
|
||||
var resp RecordEventResponse
|
||||
|
||||
if req.Sent == nil {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "Sent time is empty"
|
||||
} else if req.UserId == uuid.Nil {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "User Id is empty"
|
||||
} else if len(req.Response) == 0 {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "Response is empty"
|
||||
} else if req.ScheduledMessageEventId == uuid.Nil {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "Scheduled message event Id is empty"
|
||||
} else {
|
||||
rp.ScheduledMessageEventId = req.ScheduledMessageEventId
|
||||
rp.Response = req.Response
|
||||
rp.UserId = req.UserId
|
||||
rp.Sent = *req.Sent
|
||||
|
||||
ctx := r.Context()
|
||||
if err := e.MessageEventResponseStore.Create(ctx, &rp); err != nil {
|
||||
resp.Message = err.Error()
|
||||
statusCode = http.StatusInternalServerError
|
||||
} else {
|
||||
statusCode = http.StatusCreated
|
||||
resp.Message = "Successful"
|
||||
resp.Data = append(resp.Data, &rp)
|
||||
}
|
||||
}
|
||||
|
||||
RespondWithJSON(w, statusCode, &resp)
|
||||
}
|
||||
Reference in New Issue
Block a user