@@ -177,6 +177,75 @@ func HandleFetchProduct(rw http.ResponseWriter, r *http.Request) {
177177 }
178178}
179179
180+ func HandleUpdateProduct (rw http.ResponseWriter , r * http.Request ) {
181+ rw .Header ().Set ("Content-Type" , "application/json" )
182+
183+ scopes , scopesFound := middleware .OAuth2Scopes (r )
184+ if ! scopesFound || ! scopes .Has ([]string {"products:read" , "products:create" }) {
185+ http .Error (rw , `{"error": "insufficient scopes"}` , http .StatusForbidden )
186+ return
187+ }
188+
189+ enc := json .NewEncoder (rw )
190+ enc .SetIndent ("" , " " )
191+
192+ vars := mux .Vars (r )
193+ rawID , ok := vars ["id" ]
194+ if ! ok {
195+ http .Error (rw , `{"error": "{id} is required"}` , http .StatusBadRequest )
196+ return
197+ }
198+
199+ productID , err := strconv .ParseUint (rawID , 10 , 64 )
200+ if err != nil {
201+ http .Error (rw , `{"error": "{id} must a uint64"}` , http .StatusBadRequest )
202+ return
203+ }
204+
205+ var form ProductUpdateForm
206+ err = json .NewDecoder (r .Body ).Decode (& form )
207+ if err != nil {
208+ http .Error (rw , `{"error": "could not decode request"}` , http .StatusBadRequest )
209+ return
210+ }
211+
212+ // Seed cannot be 0 otherwise faker picks a random one
213+ faker := gofakeit .New (productID + 1 )
214+ p := faker .Product ()
215+ created := faker .DateRange (
216+ time .Date (2022 , 1 , 1 , 0 , 0 , 0 , 0 , time .UTC ),
217+ time .Date (2023 , 1 , 1 , 0 , 0 , 0 , 0 , time .UTC ),
218+ ).Truncate (24 * time .Hour )
219+ updated := faker .DateRange (
220+ created ,
221+ time .Date (2023 , 1 , 1 , 0 , 0 , 0 , 0 , time .UTC ),
222+ ).Truncate (24 * time .Hour )
223+
224+ name := p .Name
225+ if form .Name != nil {
226+ name = * form .Name
227+ }
228+ description := p .Description
229+ if form .Description != nil {
230+ description = * form .Description
231+ }
232+ price := p .Price
233+ if form .Price != nil {
234+ price = * form .Price
235+ }
236+
237+ if err := enc .Encode (Product {
238+ ID : rawID ,
239+ Name : name ,
240+ Price : price ,
241+ Description : description ,
242+ CreatedAt : created ,
243+ UpdatedAt : updated ,
244+ }); err != nil {
245+ http .Error (rw , `{"error": "could not encode response"}` , http .StatusInternalServerError )
246+ }
247+ }
248+
180249func HandleDeleteProduct (rw http.ResponseWriter , r * http.Request ) {
181250 scopes , scopesFound := middleware .OAuth2Scopes (r )
182251 if ! scopesFound || ! scopes .Has ([]string {"products:delete" }) {
0 commit comments