예제 #1
0
// CreateRegion ... create new region
func (c CommonController) CreateRegion(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	region := new(models.RegionState)
	errs := binding.Bind(req, region)
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}

	bindingErr := region.Validate(req, errs)

	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}

	// save to database
	p := models.RegionState{c.BaseModel, region.Name, region.CountryID, region.Towns}

	err := c.DataStore.SaveDatabaseObject(&p)
	if err != nil {
		panic(err)
	}

	// render response
	r.JSON(res, 200, p)
}
예제 #2
0
// UpdateRegion ... Update a Region by ID
func (c CommonController) UpdateRegion(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	vars := mux.Vars(req)
	id := vars["id"]

	region := new(models.RegionState)
	errs := binding.Bind(req, region)
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}
	queryDict, _ := c.HTTPUtilDunc.DecodeHTTPBody(req)

	bindingErr := region.Validate(req, errs)

	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}

	regionExist := &models.RegionState{}
	//query := tx.Where("id = ?", id).First(regionExist)

	qryparam := map[string]interface{}{"id": id}
	err := c.DataStore.FetchFirstGenericObject(qryparam, regionExist)

	regionExist.UpdatedAt = time.Now()

	if err != nil && err.ErrNo == 1001 {
		r.JSON(res, 404, err.Error())
	} else if err == nil {
		regionExist.Name = region.Name
		regionExist.UpdatedAt = time.Now()
		regionExist.CountryID = region.CountryID
		//UpdateDatabaseObject
		err := c.DataStore.UpdateDatabaseObject(regionExist, queryDict)
		if err != nil {
			panic(err)
		} else {
			r.JSON(res, 200, regionExist)
		}

	} else {
		fmt.Println(err.Error())
		panic(err)
	}
}