-
Notifications
You must be signed in to change notification settings - Fork 24
/
assign_template_handler.go
57 lines (45 loc) · 1.58 KB
/
assign_template_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
package notifications
import (
"encoding/json"
"net/http"
"regexp"
"github.com/cloudfoundry-incubator/notifications/v1/collections"
"github.com/cloudfoundry-incubator/notifications/v1/web/webutil"
"github.com/ryanmoran/stack"
)
type TemplateAssignment struct {
Template string `json:"template"`
}
type assignsTemplates interface {
AssignToNotification(connection collections.ConnectionInterface, clientID, notificationID, templateID string) error
}
type AssignTemplateHandler struct {
templateAssigner assignsTemplates
errorWriter errorWriter
}
func NewAssignTemplateHandler(assigner assignsTemplates, errWriter errorWriter) AssignTemplateHandler {
return AssignTemplateHandler{
templateAssigner: assigner,
errorWriter: errWriter,
}
}
func (h AssignTemplateHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, context stack.Context) {
clientID, notificationID := h.parseURL(req.URL.Path)
var templateAssignment TemplateAssignment
err := json.NewDecoder(req.Body).Decode(&templateAssignment)
if err != nil {
h.errorWriter.Write(w, webutil.ParseError{})
return
}
database := context.Get("database").(DatabaseInterface)
err = h.templateAssigner.AssignToNotification(database.Connection(), clientID, notificationID, templateAssignment.Template)
if err != nil {
h.errorWriter.Write(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h AssignTemplateHandler) parseURL(path string) (string, string) {
routeMatches := regexp.MustCompile("/clients/(.*)/notifications/(.*)/template").FindStringSubmatch(path)
return routeMatches[1], routeMatches[2]
}