Gorm和go-chi REST补丁资源

huangapple go评论81阅读模式
英文:

Gorm and go-chi REST patch resource

问题

我正在使用chigorm构建一个REST API。

我想要一个patch路由,可以只更新请求体中接收到的属性。

我不确定将这些属性传递给gorm的update方法的最佳方式是什么。

有什么好的方法可以实现这样的功能吗?

以下是处理程序方法的代码:

func (m Env) UpdateHandler(w http.ResponseWriter, r *http.Request) {
	var delta InsurancePolicy
	insurancePolicy := r.Context().Value("insurancePolicy").(InsurancePolicy)

	err := json.NewDecoder(r.Body).Decode(&delta)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	result := m.DB.Model(&insurancePolicy).Update(delta)

	if result.Error != nil {
		w.WriteHeader(http.StatusInternalServerError)
	} else {
		err := json.NewEncoder(w).Encode(insurancePolicy)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
		}
	}
}

它使用以下中间件预加载请求:

func (m Env) InsurancePolicyCtx(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var insurancePolicy InsurancePolicy
		result := m.DB.First(&insurancePolicy, chi.URLParam(r, "id"))

		if result.Error != nil {
			w.WriteHeader(http.StatusNotFound)
			return
		}

		ctx := context.WithValue(r.Context(), "insurancePolicy", insurancePolicy)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
英文:

I am building a REST API using chi and gorm

I want to have a patch route where I can update only the properties I receive in the request body.

I am not sure how is the best way of passing there properties to gorm update method.

Which would be a good way of doing so?

Here is the handler method.

func (m Env) UpdateHandler(w http.ResponseWriter, r *http.Request) {
	var delta InsurancePolicy
	insurancePolicy := r.Context().Value("insurancePolicy").(InsurancePolicy)

	err := json.NewDecoder(r.Body).Decode(&delta)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}


	result := m.DB.Model(&insurancePolicy).Update(delta)

	if result.Error != nil {
		w.WriteHeader(http.StatusInternalServerError)
	} else {
		err := json.NewEncoder(w).Encode(insurancePolicy)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
		}
	}

}

It uses this middleware to preload the request:

func (m Env) InsurancePolicyCtx(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var insurancePolicy InsurancePolicy
		result := m.DB.First(&insurancePolicy, chi.URLParam(r, "id"))

		if result.Error != nil {
			w.WriteHeader(http.StatusNotFound)
			return
		}

		ctx := context.WithValue(r.Context(), "insurancePolicy", insurancePolicy)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

答案1

得分: 1

更新非零值的正确 Gorm 方法是 Updates

英文:

The right Gorm method to use for updating non zero values is Updates

huangapple
  • 本文由 发表于 2021年7月4日 02:24:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/68238945.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定