-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
253 lines (226 loc) · 6.67 KB
/
api.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"github.com/jmoiron/sqlx"
"github.com/dxe/alc-mobile-api/model"
)
type api struct {
// query is the underlying SQL query that the API issues to the
// MySQL database. It should return a single-row, single-column JSON
// result.
query string
// args returns a pointer to a newly allocated variable able to
// store the arguments from the JSON request body.
args func() interface{}
// value returns a pointer to a newly allocated Go variable able to
// represent the JSON object returned by the query.
value func() interface{}
}
func (a *api) serve(s *server) {
var queryArgs interface{}
if a.args != nil {
args := a.args()
err := json.NewDecoder(s.r.Body).Decode(args)
if err != nil {
a.error(s, fmt.Errorf("failed to decode json request body: %w", err))
return
}
queryArgs = args
}
if a.value == nil {
if _, err := s.db.NamedExecContext(s.r.Context(), a.query, queryArgs); err != nil {
a.error(s, err)
}
return
}
// TODO(mdempsky): Implement caching and/or single-flighting (e.g.,
// golang.org/x/sync/singleflight), so we don't need to issue a DB
// request for each HTTP request.
var buf []byte
var result *sqlx.Rows
var err error
if queryArgs == nil {
result, err = s.db.QueryxContext(s.r.Context(), a.query)
} else {
result, err = s.db.NamedQueryContext(s.r.Context(), a.query, queryArgs)
}
if err != nil {
a.error(s, err)
return
}
result.Next()
if err := result.Scan(&buf); err != nil {
a.error(s, err)
return
}
if !*flagProd {
// When not in production, check that the SQL response decodes
// correctly.
// TODO(mdempsky): Replace this with unit tests.
if err := json.NewDecoder(bytes.NewReader(buf)).Decode(a.value()); err != nil {
log.Printf("failed to decode JSON response: %v", err)
}
}
s.w.Header().Set("Content-Type", "application/json; charset=utf-8")
s.w.Write(buf)
}
func (a *api) error(s *server, err error) {
s.w.Header().Set("Content-Type", "text/plain; charset=utf-8")
s.w.WriteHeader(http.StatusInternalServerError)
io.WriteString(s.w, err.Error())
}
// TODO(mdempsky): Unit tests to make sure queries below execute and
// produce valid JSON of the expected schema.
// TODO(mdempsky): The json_object argument lists are repetitive and
// somewhat redundant with the Go struct definitions. Can we use
// reflection to generate them automatically?
var apiAnnouncementList = api{
value: func() interface{} { return new([]model.Announcement) },
query: `
select json_arrayagg(json_object(
'id', a.id,
'title', a.title,
'message', a.long_message,
'icon', a.icon,
'created_by', a.created_by,
'url', a.url,
'url_text', a.url_text,
'send_time', a.send_time,
'sent', a.sent != 0` /* TODO(mdempsky): Change SQL schema to use bool. */ + `
))
from announcements a
where a.sent
and a.conference_id = :conference_id
order by send_time desc
`,
args: func() interface{} {
return new(struct {
ConferenceID int `json:"conference_id" db:"conference_id"`
})
},
}
var apiConferenceList = api{
value: func() interface{} { return new([]model.Conference) },
query: `
select json_arrayagg(json_object(
'id', c.id,
'name', c.name,
'start_date', c.start_date,
'end_date', c.end_date
))
from conferences c
order by start_date desc
`,
}
var apiEventList = api{
value: func() interface{} { return new([]model.Event) },
query: `
select json_object(
'conference', (select json_object('id', id, 'name', name, 'start_date', start_date, 'end_date', end_date) from conferences where id = :conference_id),
'events', json_arrayagg(json_object(
'id', e.id,
'name', e.name,
'description', e.description,
'start_time', e.start_time,
'length', e.length,
'key_event', e.key_event != 0,` /* TODO(mdempsky): Change SQL schema to use bool */ + `
'breakout_session', e.breakout_session != 0,` /* TODO(mdempsky): Change SQL schema to use bool */ + `
'location', json_object(
'name', l.name,
'place_id', l.place_id,
'address', l.address,
'city', l.city,
'lat', l.lat,
'lng', l.lng
),
'image_url', e.image_url,
'total_attendees', (
select count(distinct rsvpTotal.user_id)
from rsvp rsvpTotal
where rsvpTotal.event_id = e.id and rsvpTotal.attending
),
'attending', (
case when(
select attending
from rsvp rsvpStatus
where rsvpStatus.event_id = e.id and rsvpStatus.user_id = (SELECT max(id) FROM users WHERE device_id = :device_id)
) then true
else false
end
)
)))
from events e
join locations l on e.location_id = l.id
where conference_id = :conference_id
order by e.start_time asc
`,
args: func() interface{} {
return new(struct {
ConferenceID int `json:"conference_id" db:"conference_id"`
DeviceID string `json:"device_id" db:"device_id"`
})
},
}
var apiInfoList = api{
value: func() interface{} { return new([]model.Info) },
query: `
select json_arrayagg(json_object(
'id', i.id,
'title', i.title,
'subtitle', i.subtitle,
'content', i.content,
'icon', i.icon,
'image_url', i.image_url,
'display_order', i.display_order,
'key_info', i.key_info
))
from info i
order by i.display_order
`,
}
var apiUserAdd = api{
query: `
insert into users (conference_id, name, email, device_id, device_name, platform, timestamp)
values (:conference_id, :name, :email, :device_id, :device_name, :platform, now())
on duplicate key update conference_id = VALUES(conference_id), name = VALUES(name), email = VALUES(email)
`,
args: func() interface{} {
return new(struct {
ConferenceID int `json:"conference_id" db:"conference_id"`
Name string `json:"name" db:"name"`
Email string `json:"email" db:"email"`
DeviceID string `json:"device_id" db:"device_id"`
DeviceName string `json:"device_name" db:"device_name"`
DevicePlatform string `json:"platform" db:"platform"`
})
},
}
var apiEventRSVP = api{
query: `
replace into rsvp (event_id, user_id, attending, timestamp)
values (:event_id, (SELECT id FROM users WHERE device_id = :device_id), :attending, now())
`,
args: func() interface{} {
return new(struct {
EventID int `json:"event_id" db:"event_id"`
DeviceID string `json:"device_id" db:"device_id"`
Attending bool `json:"attending" db:"attending"`
})
},
}
var apiUserRegisterPushNotifications = api{
query: `
update users set expo_push_token = :expo_push_token where device_id = :device_id
`,
args: func() interface{} {
return new(struct {
DeviceID string `json:"device_id" db:"device_id"`
ExpoPushToken string `json:"expo_push_token" db:"expo_push_token"`
})
},
}