示例#1
0
// CreateTown ... create new merchant
func (c CommonController) CreateTown(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	town := new(models.Towns)
	errs := binding.Bind(req, town)
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}

	bindingErr := town.Validate(req, errs)

	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}
	// save to database
	p := models.Towns{c.BaseModel, town.RegionStateID, town.Name}

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

	// render response
	r.JSON(res, 200, p)
}
示例#2
0
// UpdateTown ... update a merchant by id
func (c CommonController) UpdateTown(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	r := render.New(render.Options{})
	vars := mux.Vars(req)
	id := vars["id"]

	town := new(models.Towns)
	errs := binding.Bind(req, town)
	if errs.Handle(res) {
		r.JSON(res, 422, errs.Error())
		return
	}

	bindingErr := town.Validate(req, errs)

	if bindingErr != nil {
		r.JSON(res, 422, bindingErr.Error())
		return
	}
	queryDict, _ := c.HTTPUtilDunc.DecodeHTTPBody(req)

	twnExist := &models.Towns{}
	qryparam := map[string]interface{}{"id": id}
	err := c.DataStore.FetchFirstGenericObject(qryparam, twnExist)
	twnExist.UpdatedAt = time.Now()

	if err != nil && err.ErrNo == 1001 {
		r.JSON(res, 404, err.Error())
	} else if err == nil {
		twnExist.Name = town.Name
		twnExist.UpdatedAt = time.Now()
		twnExist.RegionStateID = town.RegionStateID
		err := c.DataStore.UpdateDatabaseObject(twnExist, queryDict)
		if err != nil {
			panic(err)
		} else {
			r.JSON(res, 200, twnExist)
		}
	} else {
		fmt.Println(err.Error())
		panic(err)
	}
}