forked from masseelch/elk
/
read.go
48 lines (44 loc) · 1.36 KB
/
read.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Code generated by entc, DO NOT EDIT.
package http
import (
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
"github.com/mailru/easyjson"
"github.com/chestarss/elk/internal/uuid/ent"
"github.com/chestarss/elk/internal/uuid/ent/user"
"go.uber.org/zap"
)
// Read fetches the ent.User identified by a given url-parameter from the
// database and renders it to the client.
func (h *UserHandler) Read(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Read"))
// ID is URL parameter.
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
BadRequest(w, "id must be an integer")
return
}
// Create the query to fetch the User
q := h.client.User.Query().Where(user.ID(id))
e, err := q.Only(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.Int("id", id))
BadRequest(w, msg)
default:
l.Error("could not read user", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("user rendered", zap.Int("id", id))
easyjson.MarshalToHTTPResponseWriter(NewUser3451555716View(e), w)
}