-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathindex.js
460 lines (398 loc) · 12.6 KB
/
index.js
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
'use strict'
var bearerToken = require('express-bearer-token')
var cors = require('cors')
var couchbase = require('couchbase')
var express = require('express')
var jwt = require('jsonwebtoken')
var morgan = require('morgan')
var uuid = require( 'uuid')
var swaggerUi = require('swagger-ui-express')
const swaggerDocument = require('./swagger.json')
// Specify a key for JWT signing.
var JWT_KEY = 'IAMSOSECRETIVE!'
// Create a Couchbase Cluster connection
const CB = {
host: process.env.CB_HOST || 'db',
username: process.env.CB_USER || 'Administrator',
password: process.env.CB_PASS || 'password'
}
async function main() {
var cluster = await couchbase.connect(
`couchbase://${CB.host}`,
{
username: CB.username,
password: CB.password
}
)
// Open a specific Couchbase bucket, `travel-sample` in this case.
var bucket = cluster.bucket('travel-sample')
// Set up our express application
var app = express()
app.use(morgan('dev'))
app.use(cors())
app.use(express.json())
app.use('/apidocs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
var tenants = express.Router({mergeParams: true})
app.get('/', (req, res) => {
return res.send(
`<h1>Node.js Travel Sample API</h1>
A sample API for getting started with Couchbase Server and the Node.js SDK.
<ul>
<li><a href="/apidocs">Learn the API with Swagger, interactively</a>
<li><a href="https://github.com/couchbaselabs/try-cb-nodejs">GitHub</a>
</ul>`
)
})
app.get('/api/airports',
runAsync(async (req, res) => {
const searchTerm = req.query.search
let where
let options
if (searchTerm.length === 3) {
// FAA code
where = 'faa = $FAA'
options = { parameters: { FAA: searchTerm.toUpperCase() } }
} else if (
searchTerm.length === 4 &&
(searchTerm.toUpperCase() === searchTerm ||
searchTerm.toLowerCase() === searchTerm)
) {
// ICAO code
where = 'icao = $ICAO'
options = { parameters: { ICAO: searchTerm.toUpperCase() } }
} else {
// Airport name
where = 'CONTAINS(LOWER(airportname), $AIRPORT)'
options = { parameters: { AIRPORT: searchTerm.toLowerCase() } }
}
let qs = `SELECT airportname from \`travel-sample\`.inventory.airport WHERE ${ where };`
const result = await cluster.query(qs, options)
const data = result.rows
const context = [`N1QL query - scoped to inventory: ${qs}`]
return res.send({data, context})
})
)
app.get('/api/flightPaths/:from/:to',
runAsync(async (req, res) => {
const fromAirport = req.params.from
const toAirport = req.params.to
const leaveDate = new Date(req.query.leave)
const dayOfWeek = leaveDate.getDay()
let qs1 = `SELECT faa AS fromFaa
FROM \`travel-sample\`.inventory.airport
WHERE airportname = $FROM
UNION
SELECT faa AS toFaa
FROM \`travel-sample\`.inventory.airport
WHERE airportname = $TO;`
const options1 = {
parameters: {
FROM: fromAirport,
TO: toAirport,
}
}
const result = await cluster.query(qs1, options1)
const rows = result.rows
if (rows.length !== 2) {
return res.status(404).send({
error: 'One of the specified airports is invalid.',
context: [qs1],
})
}
const { fromFaa, toFaa } = { ...rows[0], ...rows[1] }
let qs2 = `
SELECT a.name, s.flight, s.utc, r.sourceairport, r.destinationairport, r.equipment
FROM \`travel-sample\`.inventory.route AS r
UNNEST r.schedule AS s
JOIN \`travel-sample\`.inventory.airline AS a ON KEYS r.airlineid
WHERE r.sourceairport = $FROM
AND r.destinationairport = $TO
AND s.day = $DAY
ORDER BY a.name ASC;
`
const options2 = {
parameters: {
FROM: fromFaa,
TO: toFaa,
DAY: dayOfWeek
}
}
const result2 = await cluster.query(qs2, options2)
const rows2 = result2.rows
if (rows2.length === 0) {
return res.status(404).send({
error: 'No flights exist between these airports.',
context: [qs1, qs2],
})
}
rows2.forEach((row) => {
row.flighttime = Math.ceil(Math.random() * 8000)
row.price = Math.ceil((row.flighttime / 8) * 100) / 100
})
return res.send({
data: rows2,
context: ["N1QL query - scoped to inventory: ", qs2],
})
})
)
app.use('/api/tenants/:tenant/', tenants)
const makeKey = key => key.toLowerCase()
tenants.route('/user/login').post(
runAsync(async (req, res) => {
const tenant = makeKey( req.params.tenant )
const user = req.body.user
const userKey = makeKey( user )
const password = req.body.password
var scope = bucket.scope(tenant)
var users = scope.collection("users")
try {
const result = await users.get(userKey)
if (result.value.password !== password) {
return res.status(401).send({
error: 'Password does not match.',
})
}
const token = jwt.sign({user}, JWT_KEY)
return res.send({
data: {token},
context: [`KV get - scoped to ${tenant}.users: for password field in document ${user}`]
})
} catch (err) {
if (err instanceof couchbase.DocumentNotFoundError) {
return res.status(401).send({
error: 'User does not exist.',
})
}
else {
throw(err)
}
}
})
)
tenants.route('/user/signup').post(
runAsync(async (req, res) => {
const user = req.body.user
const userDocKey = makeKey(user)
const password = req.body.password
const tenant = makeKey( req.params.tenant )
var scope = bucket.scope(tenant)
var users = scope.collection("users")
try {
const userDoc = {
name: user,
password: password,
flights: [],
}
await users.insert(userDocKey, userDoc)
const token = jwt.sign({user}, JWT_KEY)
return res.status(201).send({
data: {token},
context: [`KV insert - scoped to ${tenant}.users: document ${userDocKey}`]
})
} catch (err) {
if (err instanceof couchbase.DocumentExistsError) {
return res.status(409).send({
error: 'User already exists.',
})
}
else {
throw(err)
}
}
})
)
tenants.route('/user/:username/flights')
.get(authUser,
runAsync(async (req, res) => {
const username = req.params.username
const userDocKey = makeKey(username)
const tenant = makeKey( req.params.tenant )
var scope = bucket.scope(tenant)
var users = scope.collection("users")
var bookings = scope.collection("bookings")
if (username !== req.user.user) {
return res.status(401).send({
error: `Username does not match token username. ${username} VS ${req.user.user}`,
})
}
try {
const result = await users.get(userDocKey)
const ids = result.content.bookings || []
const inflated = await Promise.all(
ids.map(
async flightId => (await bookings.get(flightId)).content))
return res.send({
data: inflated,
context:
[ `KV get - scoped to ${tenant}.users: for ${ids.length} bookings in document ${userDocKey}`]
})
} catch (err) {
if (err instanceof couchbase.DocumentNotFoundError) {
return res.status(403).send({
error: 'Could not find user.',
})
}
else {
throw(err)
}
}
})
)
.put(authUser,
runAsync(async (req, res) => {
const username = req.params.username
const userDocKey = makeKey(username)
const newFlight = req.body.flights[0]
const tenant = makeKey( req.params.tenant )
var scope = bucket.scope(tenant)
var users = scope.collection("users")
var bookings = scope.collection("bookings")
if (username !== req.user.user) {
return res.status(401).send({
error: 'Username does not match token username.',
})
}
const flightId = uuid.v4()
try {
await bookings.upsert(flightId, newFlight)
}
catch (err) {
return res.status(500).send({
error: 'Failed to add flight data',
})
}
try {
await users.mutateIn(userDocKey, [
couchbase.MutateInSpec.arrayAppend(
'bookings',
flightId,
{ createPath: true })])
return res.send({
data: {
added: [ newFlight ],
},
context:
[`KV update - scoped to ${tenant}.users: for bookings subdocument field in document ${userDocKey}`]
})
} catch (err) {
if (err instanceof couchbase.DocumentNotFoundError) {
return res.status(403).send({
error: 'Could not find user.',
})
}
else {
throw(err)
}
}
})
)
app.get('/api/hotels/:description/:location?',
runAsync(async (req, res) => {
const description = req.params.description
const location = req.params.location
var scope = bucket.scope("inventory")
var hotels = scope.collection("hotel")
const qp = couchbase.SearchQuery.conjuncts([
couchbase.SearchQuery.term('hotel').field('type'),
])
if (location && location !== '*') {
qp.and(
couchbase.SearchQuery.disjuncts(
couchbase.SearchQuery.match(location).field('country'),
couchbase.SearchQuery.match(location).field('city'),
couchbase.SearchQuery.match(location).field('state'),
couchbase.SearchQuery.match(location).field('address')
)
)
}
if (description && description !== '*') {
qp.and(
couchbase.SearchQuery.disjuncts(
couchbase.SearchQuery.match(description).field('description'),
couchbase.SearchQuery.match(description).field('name')
)
)
}
const result = await cluster.searchQuery('hotels-index', qp, { limit: 100 })
const rows = result.rows
if (rows.length === 0) {
return res.send({
data: [],
context: [`FTS search - scoped to: inventory.hotel (no results)\n${JSON.stringify(qp)}`],
})
}
const addressCols = [
'address',
'state',
'city',
'country'
]
const cols = [
'type',
'name',
'description',
...addressCols
]
const results = await Promise.all(
rows.map(async (row) => {
const doc = await hotels.get(row.id, {
project: cols
})
var content = doc.content
content.address =
addressCols
.flatMap(field => content[field] || [])
.join(', ')
return content
})
)
return res.send({
data: results,
context: [
`FTS search - scoped to: inventory.hotel within fields ${cols.join(', ')}\n${JSON.stringify(qp)}`]
})
})
)
// Error handler. Must be defined after other routes/middleware
app.use((err, req, res, next) => {
const errText = err.toString()
if (errText.match(/LCB_ERR_KVENGINE_INVALID_PACKET/)) {
return res.status(500).send({
error: "Received LCB_ERR_KVENGINE_INVALID_PACKET error from Couchbase. Please check the SDK release notes and ensure you are using a compatible server version."
})
}
else {
return res.status(500).send({
error: `${err.toString()}: ${JSON.stringify(err)}`
})
}
next()
})
app.listen(8080, () => {
console.log(`Connecting to backend Couchbase server ${CB.host} with ${CB.username}/${CB.password}`)
console.log('Example app listening on port 8080!')
})
}
function authUser(req, res, next) {
bearerToken()(req, res, () => {
// Temporary Hack to extract the token from the request
req.token = req.headers.authorization.split(' ')[1]
jwt.verify(req.token, JWT_KEY, (err, decoded) => {
if (err) {
return res.status(400).send({
error: 'Invalid JWT token',
cause: err,
})
}
req.user = decoded
next()
})
})
}
function runAsync (callback) {
return function (req, res, next) {
callback(req, res, next)
.catch(next)
}
}
main()