diff --git a/api/db.go b/api/db.go index 547def3..c7d3288 100644 --- a/api/db.go +++ b/api/db.go @@ -2,6 +2,7 @@ package api import ( "errors" + "time" "git.dubyatp.xyz/chat-api-server/db" ) @@ -39,7 +40,7 @@ func dbGetMessage(id string) (*Message, error) { ID: message["ID"].(string), UserID: int64(message["UserID"].(float64)), Body: message["Body"].(string), - Timestamp: int64(message["Timestamp"].(float64)), + Timestamp: time.Time(time.Now()), }, nil } } @@ -61,7 +62,7 @@ func dbGetAllMessages() ([]*Message, error) { ID: message["ID"].(string), UserID: int64(message["UserID"].(float64)), Body: message["Body"].(string), - Timestamp: int64(message["Timestamp"].(float64)), + Timestamp: time.Time(time.Now()), }) } if len(result) == 0 { diff --git a/api/example_data.go b/api/example_data.go index 11b8d0c..db2cd52 100644 --- a/api/example_data.go +++ b/api/example_data.go @@ -1,10 +1,12 @@ package api +import "time" + var messages = []*Message{ - {ID: "1", UserID: 1, Body: "hello", Timestamp: 1234567890}, - {ID: "2", UserID: 2, Body: "world", Timestamp: 1234567890}, - {ID: "3", UserID: 1, Body: "abababa", Timestamp: 1234567890}, - {ID: "4", UserID: 2, Body: "bitch", Timestamp: 1234567890}, + {ID: "1", UserID: 1, Body: "hello", Timestamp: time.Now()}, + {ID: "2", UserID: 2, Body: "world", Timestamp: time.Now()}, + {ID: "3", UserID: 1, Body: "abababa", Timestamp: time.Now()}, + {ID: "4", UserID: 2, Body: "bitch", Timestamp: time.Now()}, } var users = []*User{ diff --git a/api/message.go b/api/message.go index fc61876..cb5d0de 100644 --- a/api/message.go +++ b/api/message.go @@ -2,10 +2,13 @@ package api import ( "context" + "encoding/json" "net/http" "github.com/go-chi/chi/v5" "github.com/go-chi/render" + + "time" ) func MessageCtx(next http.Handler) http.Handler { @@ -57,10 +60,10 @@ func ListMessages(w http.ResponseWriter, r *http.Request) { type messageKey struct{} type Message struct { - ID string `json:"id"` - UserID int64 `json:"user_id"` - Body string `json:"body"` - Timestamp int64 `json:"timestamp"` + ID string `json:"id"` + UserID int64 `json:"user_id"` + Body string `json:"body"` + Timestamp time.Time `json:"timestamp"` } type MessageRequest struct { @@ -78,3 +81,25 @@ type MessageResponse struct { Elapsed int64 `json:"elapsed"` } + +func (m MessageResponse) MarshalJSON() ([]byte, error) { + type OrderedMessageResponse struct { + ID string `json:"id"` + UserID int64 `json:"user_id"` + Body string `json:"body"` + Timestamp string `json:"timestamp"` + User *UserPayload `json:"user,omitempty"` + Elapsed int64 `json:"elapsed"` + } + + ordered := OrderedMessageResponse{ + ID: m.Message.ID, + UserID: m.Message.UserID, + Body: m.Message.Body, + Timestamp: m.Message.Timestamp.Format(time.RFC3339), + User: m.User, + Elapsed: m.Elapsed, + } + + return json.Marshal(ordered) +}