gbkannan89 commented on code in PR #7733:
URL: https://github.com/apache/trafficcontrol/pull/7733#discussion_r1307318177


##########
traffic_ops/traffic_ops_golang/origin/origins.go:
##########
@@ -487,3 +488,277 @@ func deleteQuery() string {
 WHERE id=:id`
        return query
 }
+
+// Get is the handler for GET requests to Origins of APIv5.
+func Get(w http.ResponseWriter, r *http.Request) {
+
+       var useIMS bool
+
+       inf, sysErr, userErr, errCode := api.NewInfo(r, nil, nil)
+       if sysErr != nil || userErr != nil {
+               api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+               return
+       }
+       defer inf.Close()
+
+       origins, userErr, sysErr, errCode, _ := getOrigins(w.Header(), 
inf.Params, inf.Tx, inf.User, useIMS)
+       var returnable []tc.OriginV5
+       if userErr != nil || sysErr != nil {
+               api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+               return
+       }
+
+       for _, origin := range origins {
+               returnable = append(returnable, origin.ToOriginV5())
+       }
+
+       // Assign an empty array if no origin is found instead of null.
+       if len(returnable) == 0 {
+               returnable = []tc.OriginV5{}
+       }
+
+       api.WriteResp(w, r, returnable)
+       return
+}
+
+// Create Origin with the passed data for APIv5.
+func Create(w http.ResponseWriter, r *http.Request) {
+       inf, sysError, userError, errorCode := api.NewInfo(r, nil, nil)
+       tx := inf.Tx
+       if sysError != nil || userError != nil {
+               api.HandleErr(w, r, inf.Tx.Tx, errorCode, userError, sysError)
+               return
+       }
+       defer inf.Close()
+       org, readValErr := readAndValidateJsonStruct(r)
+       if readValErr != nil {
+               api.HandleErr(w, r, tx.Tx, http.StatusBadRequest, readValErr, 
nil)
+               return
+       }
+
+       userErr, sysErr, errCode := checkTenancy(&org.TenantID, 
&org.DeliveryServiceID, tx, inf.User)
+       if userErr != nil || sysErr != nil {
+               api.HandleErr(w, r, tx.Tx, errCode, userErr, sysErr)
+               return
+       }
+
+       _, cdnName, _, err := dbhelpers.GetDSNameAndCDNFromID(inf.Tx.Tx, 
org.DeliveryServiceID)
+       if err != nil {
+               api.HandleErr(w, r, tx.Tx, http.StatusInternalServerError, nil, 
fmt.Errorf("database error: unable to retrieve delivery service name and cdn: 
%w", err))
+               return
+       }
+       userErr, sysErr, errCode = 
dbhelpers.CheckIfCurrentUserCanModifyCDN(tx.Tx, string(cdnName), 
inf.User.UserName)
+       if userErr != nil || sysErr != nil {
+               api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
+               return
+       }
+
+       resultRows, err := tx.NamedQuery(insertQuery(), org)
+       if err != nil {
+               usrErr, sysErr, code := api.ParseDBError(err)
+               api.HandleErr(w, r, tx.Tx, code, usrErr, sysErr)
+               return
+       }
+       defer resultRows.Close()
+
+       rowsAffected := 0
+       for resultRows.Next() {
+               rowsAffected++
+               if err := resultRows.Scan(&org.ID, &org.LastUpdated); err != 
nil {
+                       api.HandleErr(w, r, tx.Tx, 
http.StatusInternalServerError, fmt.Errorf("origin create: scanning: 
"+err.Error()), nil)
+                       return
+               }
+       }
+       if rowsAffected == 0 {
+               api.HandleErr(w, r, tx.Tx, http.StatusInternalServerError, 
fmt.Errorf("origin create: scanning: %w", err), nil)
+               return
+       } else if rowsAffected > 1 {
+               api.HandleErr(w, r, tx.Tx, http.StatusInternalServerError, 
fmt.Errorf("origin create: multiple rows returned"), nil)
+               return
+       }
+
+       alerts := tc.CreateAlerts(tc.SuccessLevel, "origin was created.")
+       w.Header().Set("Location", fmt.Sprintf("/api/%d.%d/origins?id=%d", 
inf.Version.Major, inf.Version.Minor, org.ID))
+       api.WriteAlertsObj(w, r, http.StatusCreated, alerts, org)
+}
+
+// Update a Origin for APIv5.
+func Update(w http.ResponseWriter, r *http.Request) {
+       inf, sysError, userError, errorCode := api.NewInfo(r, []string{"id"}, 
[]string{"id"})
+       tx := inf.Tx
+       if sysError != nil || userError != nil {
+               api.HandleErr(w, r, inf.Tx.Tx, errorCode, userError, sysError)
+               return
+       }
+       defer inf.Close()
+
+       origin, readValErr := readAndValidateJsonStruct(r)
+       if readValErr != nil {
+               api.HandleErr(w, r, tx.Tx, http.StatusBadRequest, readValErr, 
nil)
+               return
+       }
+       userErr, sysErr, errCode := checkTenancy(&origin.TenantID, 
&origin.DeliveryServiceID, tx, inf.User)
+       if userErr != nil || sysErr != nil {
+               api.HandleErr(w, r, tx.Tx, errCode, userErr, sysErr)
+               return
+       }
+
+       isPrimary := false
+       ds := 0
+       var existingLastUpdated time.Time
+
+       requestedOriginId := inf.IntParams["id"]
+
+       q := `SELECT is_primary, deliveryservice, last_updated FROM origin 
WHERE id = $1`
+       errLookup := tx.QueryRow(q, requestedOriginId).Scan(&isPrimary, &ds, 
&existingLastUpdated)
+       if errLookup != nil {
+               if errors.Is(errLookup, sql.ErrNoRows) {
+                       api.HandleErr(w, r, tx.Tx, http.StatusNotFound, 
fmt.Errorf("origin not found"), nil)
+                       return
+               }
+               api.HandleErr(w, r, tx.Tx, http.StatusInternalServerError, nil, 
fmt.Errorf("database error: %w, when checking if origin with id %d exists", 
errLookup, requestedOriginId))
+               return
+       }
+       // check if the entity was already updated
+       userErr, sysErr, errCode = api.CheckIfUnModified(r.Header, inf.Tx, 
requestedOriginId, "origin")
+       if userErr != nil || sysErr != nil {
+               api.HandleErr(w, r, tx.Tx, errCode, userErr, sysErr)
+               return
+       }
+
+       if isPrimary && origin.DeliveryServiceID != ds {
+               api.HandleErr(w, r, tx.Tx, http.StatusBadRequest, 
fmt.Errorf("cannot update the delivery service of a primary origin"), nil)
+               return
+       }
+
+       _, cdnName, _, err := dbhelpers.GetDSNameAndCDNFromID(tx.Tx, 
origin.DeliveryServiceID)
+       if err != nil {
+               api.HandleErr(w, r, tx.Tx, http.StatusInternalServerError, err, 
nil)
+               return
+       }
+       userErr, sysErr, errCode = 
dbhelpers.CheckIfCurrentUserCanModifyCDN(tx.Tx, string(cdnName), 
inf.User.UserName)
+       if userErr != nil || sysErr != nil {
+               api.HandleErr(w, r, tx.Tx, errCode, userErr, sysErr)
+               return
+       }
+
+       var lastUpdated time.Time
+       query := `UPDATE origin SET
+                                       cachegroup=$1,
+                                       coordinate=$2,
+                                       deliveryservice=$3,
+                                       fqdn=$4,
+                                       ip6_address=$5,
+                                       ip_address=$6,
+                                       name=$7,
+                                       port=$8,
+                                       profile=$9,
+                                       protocol=$10,
+                                       tenant=$11
+                                       WHERE id=$12 RETURNING last_updated`
+       errUpdate := tx.QueryRow(query, origin.CachegroupID, 
origin.CoordinateID, origin.DeliveryServiceID,
+               origin.FQDN, origin.IP6Address, origin.IPAddress, origin.Name,
+               origin.Port, origin.ProfileID, origin.Protocol, 
origin.TenantID, requestedOriginId).Scan(&lastUpdated)
+       if errUpdate != nil {
+               if errors.Is(errUpdate, sql.ErrNoRows) {
+                       api.HandleErr(w, r, tx.Tx, http.StatusBadRequest, 
fmt.Errorf("origin: %d not found", requestedOriginId), nil)
+                       return
+               }
+               usrErr, sysErr, code := api.ParseDBError(errUpdate)
+               api.HandleErr(w, r, tx.Tx, code, usrErr, sysErr)
+               return
+       }
+
+       origin.LastUpdated = lastUpdated
+       alerts := tc.CreateAlerts(tc.SuccessLevel, "origin was updated.")
+       api.WriteAlertsObj(w, r, http.StatusOK, alerts, origin)
+       return
+}
+
+// Delete an Origin for APIv5.
+func Delete(w http.ResponseWriter, r *http.Request) {
+       inf, userErr, sysErr, errCode := api.NewInfo(r, nil, nil)
+       tx := inf.Tx.Tx
+       if userErr != nil || sysErr != nil {
+               api.HandleErr(w, r, tx, errCode, userErr, sysErr)
+               return
+       }
+       defer inf.Close()
+
+       id := inf.Params["id"]
+       errsValid := tovalidate.ToErrors(validation.Errors{
+               "id": validation.Validate(id, validation.NilOrNotEmpty),
+       })
+
+       if len(errsValid) > 0 {
+               api.HandleErr(w, r, tx, http.StatusBadRequest, 
fmt.Errorf("missing key: id"), nil)
+               return
+       }

Review Comment:
   i did because if id is not given in delete it is now throughing internal 
server error instead thought of showing an error msg. still i should have got 
id as IntParam



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to