This repository has been archived by the owner on Feb 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
create.go
61 lines (57 loc) · 1.55 KB
/
create.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
49
50
51
52
53
54
55
56
57
58
59
60
61
// Code generated by entc, DO NOT EDIT.
package http
import (
"net/http"
"github.com/mailru/easyjson"
"github.com/masseelch/elk/internal/uuid/ent"
"github.com/masseelch/elk/internal/uuid/ent/user"
"go.uber.org/zap"
)
// Create creates a new ent.User and stores it in the database.
func (h UserHandler) Create(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Create"))
// Get the post data.
var d UserCreateRequest
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
l.Error("error decoding json", zap.Error(err))
BadRequest(w, "invalid json string")
return
}
// Save the data.
b := h.client.User.Create()
if d.UUID != nil {
b.SetUUID(*d.UUID)
}
e, err := b.Save(r.Context())
if err != nil {
switch {
default:
l.Error("could not create user", zap.Error(err))
InternalServerError(w, nil)
}
return
}
// Store id of fresh entity to log errors for the reload.
id := e.ID
// Reload entry.
q := h.client.User.Query().Where(user.ID(e.ID))
ret, 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(ret), w)
}