@@ -5,8 +5,10 @@ import (
55 "errors"
66 "fmt"
77 "net/http"
8+ "strconv"
89
910 "github.com/go-chi/chi/v5"
11+ "github.com/raphico/go-device-telemetry-api/internal/common/pagination"
1012 "github.com/raphico/go-device-telemetry-api/internal/domain/command"
1113 "github.com/raphico/go-device-telemetry-api/internal/domain/device"
1214 "github.com/raphico/go-device-telemetry-api/internal/logger"
@@ -29,7 +31,7 @@ type createCommandRequest struct {
2931 Payload any `json:"payload"`
3032}
3133
32- type createCommandResponse struct {
34+ type commandResponse struct {
3335 ID string `json:"id"`
3436 CommandName string `json:"command_name"`
3537 Payload any `json:"payload"`
@@ -74,7 +76,7 @@ func (h *CommandHandler) HandleCreateCommand(w http.ResponseWriter, r *http.Requ
7476 return
7577 }
7678
77- res := createCommandResponse {
79+ res := commandResponse {
7880 ID : c .ID .String (),
7981 CommandName : c .Name .String (),
8082 Payload : c .Payload ,
@@ -83,3 +85,61 @@ func (h *CommandHandler) HandleCreateCommand(w http.ResponseWriter, r *http.Requ
8385
8486 WriteJSON (w , http .StatusCreated , res , nil )
8587}
88+
89+ func (h * CommandHandler ) HandleGetDeviceCommands (w http.ResponseWriter , r * http.Request ) {
90+ deviceIDStr := chi .URLParam (r , "device_id" )
91+ deviceID , err := device .NewDeviceID (deviceIDStr )
92+ if err != nil {
93+ WriteJSONError (w , http .StatusBadRequest , invalidRequest , "invalid device id" )
94+ return
95+ }
96+
97+ limit := pagination .DefaultLimit
98+ if limitStr := r .URL .Query ().Get ("limit" ); limitStr != "" {
99+ if v , err := strconv .Atoi (limitStr ); err != nil || v < 0 {
100+ WriteJSONError (w , http .StatusBadRequest , invalidRequest , "limit must be a positive integer" )
101+ return
102+ } else {
103+ limit = pagination .ClampLimit (v )
104+ }
105+ }
106+
107+ var cur * pagination.Cursor
108+ if cstr := r .URL .Query ().Get ("cursor" ); cstr != "" {
109+ if decoded , err := pagination .Decode (cstr ); err != nil {
110+ WriteJSONError (w , http .StatusBadRequest , invalidRequest , err .Error ())
111+ return
112+ } else {
113+ cur = & decoded
114+ }
115+ }
116+
117+ commands , next , err := h .command .ListDeviceCommands (r .Context (), deviceID , limit , cur )
118+ if err != nil {
119+ h .log .Error (fmt .Sprintf ("failed to get device commands: %v" , err ))
120+ WriteInternalError (w )
121+ return
122+ }
123+
124+ out := make ([]commandResponse , 0 , len (commands ))
125+ for _ , c := range commands {
126+ out = append (out , commandResponse {
127+ ID : c .ID .String (),
128+ CommandName : c .Name .String (),
129+ Payload : c .Payload ,
130+ Status : c .Status .String (),
131+ })
132+ }
133+
134+ var nextStr string
135+ if next != nil {
136+ nextStr = pagination .Encode (* next )
137+ }
138+
139+ meta := pageMeta {
140+ NextCursor : nextStr ,
141+ Limit : limit ,
142+ }
143+
144+ WriteJSON (w , http .StatusOK , out , meta )
145+ }
0 commit comments