-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.go
101 lines (89 loc) · 2.41 KB
/
handler.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package natsdb
import (
"encoding/json"
"github.com/nats-io/go-nats"
)
var err error
// Handler : this struct manages all nats connections and maps them
// to the injected entity
type Handler struct {
Nats *nats.Conn
NewModel func() Model
NotFoundErrorMessage []byte
UnexpectedErrorMessage []byte
DeletedMessage []byte
}
// Find : Based on the fields of the input json it will
// search and return any entity matching these fields
func (h *Handler) Find(msg *nats.Msg) {
e := h.NewModel()
e.MapInput(msg.Data)
entities := e.Find()
body, err := json.Marshal(&entities)
if err != nil {
h.Nats.Publish(msg.Reply, h.UnexpectedErrorMessage)
return
}
h.Nats.Publish(msg.Reply, body)
}
// Get : Based on a json input with an id field will
// return the client details for this id
func (h *Handler) Get(msg *nats.Msg) {
e := h.NewModel()
if ok := e.LoadFromInputOrFail(msg, h); ok {
body, err := json.Marshal(e)
if err != nil {
h.Fail(msg)
}
h.Nats.Publish(msg.Reply, body)
}
}
// Del : Based on a json input with an id field will
// delete the client details for this id
func (h *Handler) Del(msg *nats.Msg) {
e := h.NewModel()
if ok := e.LoadFromInputOrFail(msg, h); ok {
e.Delete()
h.Nats.Publish(msg.Reply, h.DeletedMessage)
}
}
// Set : Based on a json input with an id field will
// update the client details for this id with all extra fields
// defined on the message
func (h *Handler) Set(msg *nats.Msg) {
e := h.NewModel()
if ok := e.LoadFromInput(msg.Data); ok {
err = e.Update(msg.Data)
if err != nil {
h.Fail(msg)
}
body, err := json.Marshal(e)
if err != nil {
h.Fail(msg)
}
h.Nats.Publish(msg.Reply, body)
} else {
input := h.NewModel()
input.MapInput(msg.Data)
if input.HasID() == false {
if err = e.Save(); err != nil {
h.Nats.Publish(msg.Reply, []byte(err.Error()))
} else {
body, err := json.Marshal(e)
if err != nil {
h.Fail(msg)
}
h.Nats.Publish(msg.Reply, body)
}
} else {
h.Nats.Publish(msg.Reply, h.NotFoundErrorMessage)
}
}
}
// Fail : It replies the nats message with a not found error
func (h *Handler) Fail(msg *nats.Msg) {
h.Nats.Publish(msg.Reply, h.NotFoundErrorMessage)
}