-
Notifications
You must be signed in to change notification settings - Fork 2
/
handlers.go
225 lines (190 loc) · 6.45 KB
/
handlers.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package concepts
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"strings"
ontology "github.com/Financial-Times/cm-graph-ontology/v2"
transactionidutils "github.com/Financial-Times/transactionid-utils-go"
"github.com/Financial-Times/up-rw-app-api-go/rwapi"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
var irregularConceptTypePaths = map[string]string{
"AlphavilleSeries": "alphaville-series",
"BoardRole": "membership-roles",
"Dummy": "dummies",
"Person": "people",
"PublicCompany": "organisations",
"NAICSIndustryClassification": "industry-classifications",
"FTAnIIndustryClassification": "industry-classifications",
}
type ConceptsHandler struct {
ConceptsService ConceptServicer
}
func (h *ConceptsHandler) RegisterHandlers(router *mux.Router) {
router.Handle("/{concept_type}/{uuid}", handlers.MethodHandler{
"GET": http.HandlerFunc(h.GetConcept),
"PUT": http.HandlerFunc(h.PutConcept),
"DELETE": http.HandlerFunc(h.DeleteConcept),
})
}
func (h *ConceptsHandler) PutConcept(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
uuid := vars["uuid"]
conceptType := vars["concept_type"]
transID := transactionidutils.GetTransactionIDFromRequest(r)
w.Header().Add("Content-Type", "application/json")
w.Header().Set("X-Request-Id", transID)
var body io.Reader = r.Body
dec := json.NewDecoder(body)
inst, docUUID, err := h.ConceptsService.DecodeJSON(dec)
if err != nil {
writeJSONError(w, err.Error(), http.StatusBadRequest)
return
}
if docUUID != uuid {
writeJSONError(w, fmt.Sprintf("Uuids from payload and request, respectively, do not match: '%v' '%v'", docUUID, uuid), http.StatusBadRequest)
return
}
agConcept := inst.(ontology.CanonicalConcept)
if err := checkConceptTypeAgainstPath(agConcept.Type, conceptType); err != nil {
writeJSONError(w, err.Error(), http.StatusBadRequest)
return
}
updatedIds, err := h.ConceptsService.Write(inst, transID)
if err != nil {
switch e := err.(type) {
case noContentReturnedError:
writeJSONError(w, e.NoContentReturnedDetails(), http.StatusNoContent)
return
case rwapi.ConstraintOrTransactionError:
writeJSONError(w, e.Error(), http.StatusConflict)
return
case invalidRequestError:
writeJSONError(w, e.InvalidRequestDetails(), http.StatusBadRequest)
return
default:
writeJSONError(w, err.Error(), http.StatusServiceUnavailable)
return
}
}
updateIDsBody, err := json.Marshal(updatedIds)
if err != nil {
writeJSONError(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(updateIDsBody)
return
}
func (h *ConceptsHandler) GetConcept(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
uuid := vars["uuid"]
conceptType := vars["concept_type"]
transID := transactionidutils.GetTransactionIDFromRequest(r)
obj, found, err := h.ConceptsService.Read(uuid, transID)
w.Header().Add("Content-Type", "application/json")
w.Header().Set("X-Request-Id", transID)
if err != nil {
writeJSONError(w, err.Error(), http.StatusServiceUnavailable)
return
}
if !found {
writeJSONError(w, fmt.Sprintf("Concept with prefUUID %s not found in db.", uuid), http.StatusNotFound)
return
}
agConcept := obj.(ontology.CanonicalConcept)
if err := checkConceptTypeAgainstPath(agConcept.Type, conceptType); err != nil {
writeJSONError(w, err.Error(), http.StatusBadRequest)
return
}
enc := json.NewEncoder(w)
if err := enc.Encode(obj); err != nil {
writeJSONError(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (h *ConceptsHandler) DeleteConcept(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
uuid := vars["uuid"]
conceptType := vars["concept_type"]
transID := transactionidutils.GetTransactionIDFromRequest(r)
w.Header().Add("Content-Type", "application/json")
w.Header().Set("X-Request-Id", transID)
// Validate that the concept exists and is of the right type.
obj, found, err := h.ConceptsService.Read(uuid, transID)
if err != nil {
writeJSONError(w, err.Error(), http.StatusServiceUnavailable, uuid)
return
}
if !found {
writeJSONError(w, fmt.Sprintf("Concept with prefUUID %s not found in db.", uuid), http.StatusNotFound, uuid)
return
}
agConcept := obj.(ontology.CanonicalConcept)
if err := checkConceptTypeAgainstPath(agConcept.Type, conceptType); err != nil {
writeJSONError(w, err.Error(), http.StatusBadRequest, uuid)
return
}
// Delete the concept
affected, err := h.ConceptsService.Delete(uuid, transID)
if errors.Is(err, ErrNotFound) {
writeJSONError(w, fmt.Sprintf("Concept with prefUUID %s not found in db.", uuid), http.StatusNotFound, uuid)
return
}
if errors.Is(err, ErrDeleteRelated) {
writeJSONError(w, fmt.Sprintf("Concept with prefUUID %s is referenced by %q, remove these before deleting.", uuid, affected), http.StatusBadRequest, affected...)
return
}
if errors.Is(err, ErrDeleteSource) {
writeJSONError(w, fmt.Sprintf("Concept with UUID %s is a source concept, the canonical concept %q should be deleted instead.", uuid, affected[0]), http.StatusBadRequest, affected...)
return
}
if err != nil {
writeJSONError(w, err.Error(), http.StatusServiceUnavailable, uuid)
return
}
resp := struct {
UUIDS []string `json:"uuids"`
}{affected}
enc := json.NewEncoder(w)
if err := enc.Encode(resp); err != nil {
writeJSONError(w, err.Error(), http.StatusInternalServerError, uuid)
return
}
}
type errorResponse struct {
Message string `json:"message,omitempty"`
UUIDs []string `json:"uuids,omitempty"`
}
func writeJSONError(w http.ResponseWriter, errorMsg string, statusCode int, uuids ...string) {
w.WriteHeader(statusCode)
errorResp := errorResponse{errorMsg, uuids}
enc := json.NewEncoder(w)
if err := enc.Encode(errorResp); err != nil {
return
}
}
func checkConceptTypeAgainstPath(conceptType, path string) error {
if iPath, ok := irregularConceptTypePaths[conceptType]; ok && iPath != "" {
if iPath != path {
return errors.New("concept type does not match path")
}
return nil
}
if toSnakeCase(conceptType)+"s" != path {
return errors.New("concept type does not match path")
}
return nil
}
var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
func toSnakeCase(str string) string {
snake := matchFirstCap.ReplaceAllString(str, "${1}-${2}")
snake = matchAllCap.ReplaceAllString(snake, "${1}-${2}")
return strings.ToLower(snake)
}