コード例 #1
0
func (sc *ServiceControllerImpl) get(w http.ResponseWriter, r *http.Request) (serviceResult, error) {
	if !bson.IsObjectIdHex(mux.Vars(r)["id"]) {
		return serviceResult{}, errors.New("Not a valid ID.")
	}
	service := new(models.Service)
	db := sc.database.Get(r)
	if err := service.FindByID(bson.ObjectIdHex(mux.Vars(r)["id"]), db); !service.ID.Valid() || err != nil {
		return serviceResult{}, errors.New("No such service.")
	}
	defer service.WasSelected(db)

	refCode := new(models.ReferralCode)
	if err := refCode.FindRandom(service.ID, db); err != nil {
		return serviceResult{}, errors.New("Internal error.")
	} else {
		defer refCode.WasViewed(db)
	}

	userRefCode := new(models.ReferralCode)
	if user := sc.currentUser.Get(r); user != nil {
		userRefCode.FindByUserAndService(sc.currentUser.Get(r).ID, service.ID, db)
	}

	return serviceResult{service, refCode, userRefCode}, nil
}
コード例 #2
0
func (rc *ReferralCodeControllerImpl) create(w http.ResponseWriter, r *http.Request) {
	body, _ := ioutil.ReadAll(r.Body)
	var values map[string]string
	json.Unmarshal(body, &values)

	// verify serviceID
	rawServiceID := values["serviceId"]
	if !bson.IsObjectIdHex(rawServiceID) {
		rc.renderer.JSON(w, http.StatusBadRequest, map[string]string{
			"error": "Bad service ID",
		})
		return
	}

	db := rc.database.Get(r)
	service := new(models.Service)
	serviceID := bson.ObjectIdHex(rawServiceID)
	if err := service.FindByID(serviceID, db); err != nil || !service.ID.Valid() {
		rc.renderer.JSON(w, http.StatusBadRequest, map[string]string{
			"error": "Bad service request",
		})
		return
	}

	userID := rc.currentUser.Get(r).ID
	code := values["code"]
	refCode := new(models.ReferralCode)
	if refCode.FindByUserAndService(userID, serviceID, db); refCode.ID.Valid() {
		if code == "" {
			analytics := new(models.Analytics)
			defer analytics.AddDeletedReferralCode(refCode, db)
			defer refCode.Delete(db)

			rc.renderer.JSON(w, http.StatusOK, nil)
			return
		}

		if err := refCode.Edit(code, db); err != nil {
			rc.renderer.JSON(w, http.StatusBadRequest, map[string]string{
				"error": err.Error(),
			})
			return
		}
	} else {
		if code == "" {
			rc.renderer.JSON(w, http.StatusBadRequest, map[string]string{
				"error": "Empty referral code not allowed",
			})
			return
		}
		refCode = models.NewReferralCode(code, rc.currentUser.Get(r).ID, service.ID)
		if err := refCode.Save(db); err != nil {
			rc.renderer.JSON(w, http.StatusBadRequest, map[string]string{
				"error": err.Error(),
			})
			return
		}
	}

	rc.renderer.JSON(w, http.StatusCreated, refCode)
}