Exemplo n.º 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
}
func (rc *ReferralCodeControllerImpl) randomCode(serviceID bson.ObjectId, db *mgo.Database, w http.ResponseWriter) *models.ReferralCode {
	refCode := new(models.ReferralCode)

	service := new(models.Service)
	if err := service.FindByID(serviceID, db); err != nil {
		rc.renderer.JSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return refCode
	}
	if !service.ID.Valid() {
		rc.renderer.JSON(w, http.StatusBadRequest, map[string]string{"error": "No such service."})
		return refCode
	}

	if err := refCode.FindRandom(service.ID, db); err != nil {
		rc.renderer.JSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return refCode
	}
	defer refCode.WasViewed(db)

	return refCode
}