コード例 #1
0
ファイル: address.go プロジェクト: ninnemana/API
func SetDefaultAddress(w http.ResponseWriter, req *http.Request, params martini.Params, enc encoding.Encoder, shop *cart.Shop) string {

	var c cart.Customer

	customerId := params["id"]
	if !bson.IsObjectIdHex(customerId) {
		apierror.GenerateError("invalid customer reference", nil, w, req)
		return ""
	}

	c.Id = bson.ObjectIdHex(customerId)
	c.ShopId = shop.Id
	if err := c.Get(); err != nil {
		apierror.GenerateError("", err, w, req)
		return ""
	}

	addressId := params["address"]
	if !bson.IsObjectIdHex(addressId) {
		apierror.GenerateError("invalid address reference", nil, w, req)
		return ""
	}

	found := false
	for _, addr := range c.Addresses {
		if addr.Id.Hex() == addressId {
			c.DefaultAddress = &addr
			found = true
			break
		}
	}

	if !found {
		apierror.GenerateError("invalid address reference", nil, w, req)
		return ""
	}

	if err := c.Update(); err != nil {
		apierror.GenerateError(err.Error(), err, w, req)
		return ""
	}

	return encoding.Must(enc.Encode(c))
}