-
Notifications
You must be signed in to change notification settings - Fork 12
/
server.go
293 lines (261 loc) · 8.92 KB
/
server.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/neo4j/neo4j-go-driver/v5/neo4j"
)
type MovieResult struct {
Movie `json:"movie"`
}
type VoteResult struct {
Updates int `json:"updates"`
}
type Movie struct {
Released int64 `json:"released"`
Title string `json:"title,omitempty"`
Tagline string `json:"tagline,omitempty"`
Votes int64 `json:"votes,omitempty"`
Cast []Person `json:"cast,omitempty"`
}
type Person struct {
Job string `json:"job"`
Role []string `json:"role"`
Name string `json:"name"`
}
type D3Response struct {
Nodes []Node `json:"nodes"`
Links []Link `json:"links"`
}
type Node struct {
Title string `json:"title"`
Label string `json:"label"`
}
type Link struct {
Source int `json:"source"`
Target int `json:"target"`
}
type Neo4jConfiguration struct {
Url string
Username string
Password string
Database string
}
func (nc *Neo4jConfiguration) newDriver() (neo4j.DriverWithContext, error) {
return neo4j.NewDriverWithContext(nc.Url, neo4j.BasicAuth(nc.Username, nc.Password, ""))
}
func defaultHandler(w http.ResponseWriter, req *http.Request) {
_, file, _, _ := runtime.Caller(0)
page := filepath.Join(filepath.Dir(file), "public", "index.html")
if body, err := os.ReadFile(page); err != nil {
w.WriteHeader(500)
w.Header().Set("Content-Type", "text/plain")
_, _ = w.Write([]byte(err.Error()))
} else {
w.Header().Set("Content-Type", "text/html;charset=utf-8")
_, _ = w.Write(body)
}
}
func searchHandlerFunc(ctx context.Context, driver neo4j.DriverWithContext, database string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
result, err := neo4j.ExecuteQuery(ctx, driver, `MATCH (movie:Movie)
WHERE toLower(movie.title) CONTAINS toLower($title)
RETURN movie.title AS title, movie.tagline AS tagline, movie.votes AS votes, movie.released AS released`,
map[string]interface{}{"title": req.URL.Query().Get("q")},
neo4j.EagerResultTransformer,
neo4j.ExecuteQueryWithReadersRouting(),
neo4j.ExecuteQueryWithDatabase(database))
if err != nil {
log.Println("error querying search:", err)
return
}
movies := make([]MovieResult, len(result.Records))
for i, record := range result.Records {
released, _, _ := neo4j.GetRecordValue[int64](record, "released")
title, _, _ := neo4j.GetRecordValue[string](record, "title")
tagline, _, _ := neo4j.GetRecordValue[string](record, "tagline")
votes, _, _ := neo4j.GetRecordValue[int64](record, "votes")
movies[i] = MovieResult{Movie{Released: released, Title: title, Tagline: tagline, Votes: votes}}
}
err = json.NewEncoder(w).Encode(movies)
if err != nil {
log.Println("error writing search response:", err)
}
}
}
func movieHandlerFunc(ctx context.Context, driver neo4j.DriverWithContext, database string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
title, _ := url.QueryUnescape(req.URL.Path[len("/movie/"):])
result, err := neo4j.ExecuteQuery(ctx, driver, `MATCH (movie:Movie {title:$title})
OPTIONAL MATCH (movie)<-[r]-(person:Person)
WITH movie.title AS title,
collect({
name:person.name,
job: head(split(toLower(type(r)),'_')),
role: r.roles
}) AS cast
LIMIT 1
UNWIND cast as c
RETURN title, c.name as name, c.job as job, c.role as role`,
map[string]interface{}{"title": title},
neo4j.EagerResultTransformer,
neo4j.ExecuteQueryWithReadersRouting(),
neo4j.ExecuteQueryWithDatabase(database))
var movie Movie
for _, record := range result.Records {
title, _, _ := neo4j.GetRecordValue[string](record, "title")
movie.Title = title
name, _, _ := neo4j.GetRecordValue[string](record, "name")
job, _, _ := neo4j.GetRecordValue[string](record, "job")
role, _ := record.Get("role")
switch role.(type) {
case []any:
movie.Cast = append(movie.Cast, Person{Name: name, Job: job, Role: toStringSlice(role.([]any))})
default: // handle nulls or unexpected stuff
movie.Cast = append(movie.Cast, Person{Name: name, Job: job})
}
}
if err != nil {
log.Println("error querying movie:", err)
return
}
err = json.NewEncoder(w).Encode(movie)
if err != nil {
log.Println("error writing movie response:", err)
}
}
}
func voteInMovieHandlerFunc(ctx context.Context, driver neo4j.DriverWithContext, database string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
title, _ := url.QueryUnescape(req.URL.Path[len("/movie/vote/"):])
result, err := neo4j.ExecuteQuery(ctx, driver, `MATCH (m:Movie {title: $title})
SET m.votes = coalesce(m.votes, 0) + 1`,
map[string]interface{}{"title": title},
neo4j.EagerResultTransformer,
neo4j.ExecuteQueryWithDatabase(database))
var vote VoteResult
vote.Updates = result.Summary.Counters().PropertiesSet()
if err != nil {
log.Println("error voting for movie:", err)
return
}
err = json.NewEncoder(w).Encode(vote)
if err != nil {
log.Println("error writing vote result response:", err)
}
}
}
func graphHandler(ctx context.Context, driver neo4j.DriverWithContext, database string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
result, err := neo4j.ExecuteQuery(ctx, driver, `MATCH (m:Movie)<-[:ACTED_IN]-(a:Person)
RETURN m.title AS movie, collect(a.name) AS cast
LIMIT $limit `,
map[string]interface{}{"limit": parseLimit(req)},
neo4j.EagerResultTransformer,
neo4j.ExecuteQueryWithReadersRouting(),
neo4j.ExecuteQueryWithDatabase(database))
var d3Response D3Response
allActors := make(map[string]int)
for _, record := range result.Records {
title, _, _ := neo4j.GetRecordValue[string](record, "movie")
cast, _, _ := neo4j.GetRecordValue[[]any](record, "cast")
d3Response.Nodes = append(d3Response.Nodes, Node{Title: title, Label: "movie"})
movieIndex := len(d3Response.Nodes) - 1
for _, actor := range cast {
actorName := actor.(string)
if actorIndex, found := allActors[actorName]; found {
d3Response.Links = append(d3Response.Links, Link{Source: actorIndex, Target: movieIndex})
} else {
d3Response.Nodes = append(d3Response.Nodes, Node{Title: actorName, Label: "actor"})
newActorIndex := len(d3Response.Nodes) - 1
d3Response.Links = append(d3Response.Links, Link{Source: newActorIndex, Target: movieIndex})
allActors[actorName] = newActorIndex
}
}
}
if err != nil {
log.Println("error querying graph:", err)
return
}
err = json.NewEncoder(w).Encode(d3Response)
if err != nil {
log.Println("error writing graph response:", err)
}
}
}
func toStringSlice(slice []interface{}) []string {
var result []string
for _, e := range slice {
result = append(result, e.(string))
}
return result
}
func main() {
ctx := context.Background()
configuration := parseConfiguration()
driver, err := configuration.newDriver()
if err != nil {
log.Fatal(err)
}
defer unsafeClose(ctx, driver)
serveMux := http.NewServeMux()
serveMux.HandleFunc("/", defaultHandler)
serveMux.HandleFunc("/search", searchHandlerFunc(ctx, driver, configuration.Database))
serveMux.HandleFunc("/movie/vote/", voteInMovieHandlerFunc(ctx, driver, configuration.Database))
serveMux.HandleFunc("/movie/", movieHandlerFunc(ctx, driver, configuration.Database))
serveMux.HandleFunc("/graph", graphHandler(ctx, driver, configuration.Database))
var port string
var found bool
if port, found = os.LookupEnv("PORT"); !found {
port = "8080"
}
fmt.Printf("Running on port %s, database is at %s\n", port, configuration.Url)
panic(http.ListenAndServe(":"+port, serveMux))
}
func parseLimit(req *http.Request) int {
limits := req.URL.Query()["limit"]
limit := 50
if len(limits) > 0 {
var err error
if limit, err = strconv.Atoi(limits[0]); err != nil {
limit = 50
}
}
return limit
}
func parseConfiguration() *Neo4jConfiguration {
database := lookupEnvOrGetDefault("NEO4J_DATABASE", "movies")
if !strings.HasPrefix(lookupEnvOrGetDefault("NEO4J_VERSION", "4"), "4") {
database = ""
}
return &Neo4jConfiguration{
Url: lookupEnvOrGetDefault("NEO4J_URI", "neo4j+s://demo.neo4jlabs.com"),
Username: lookupEnvOrGetDefault("NEO4J_USER", "movies"),
Password: lookupEnvOrGetDefault("NEO4J_PASSWORD", "movies"),
Database: database,
}
}
func lookupEnvOrGetDefault(key string, defaultValue string) string {
if env, found := os.LookupEnv(key); !found {
return defaultValue
} else {
return env
}
}
func unsafeClose(ctx context.Context, closeable interface{ Close(context.Context) error }) {
if err := closeable.Close(ctx); err != nil {
log.Fatal(fmt.Errorf("could not close resource: %w", err))
}
}