-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
85 lines (69 loc) · 1.76 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
const { send } = require('micro')
const uuid = require('uuid')
const {
router,
get,
post,
head
} = require('microrouter')
const { PENDING, REDEEMED } = require('./statuses')
const rethinkDB = require('rethinkdb')
let rethinkDBConnection
rethinkDB.connect({ host: 'localhost', port: 32775 }, (err, connection) => {
if(err) throw err
rethinkDBConnection = connection
})
const create = async (req, res) => {
let invitation = Object.assign({
hash: uuid.v1(),
status: PENDING
}, req.body)
await rethinkDB.table('invitations')
.insert(invitation)
.run(rethinkDBConnection, err => {
if (err) throw err
})
send(res, 201, invitation)
}
const redeem = async (req, res) => {
const { hash } = req.params
let invitation
await rethinkDB.table('invitations')
.filter({ hash })
.update({ status: REDEEMED }, { returnChanges: true })
.run(rethinkDBConnection, (err, result) => {
if (err) throw err
invitation = result
})
if (!invitation.changes) {
send(res, 404, 'Invitation not found')
} else if (!invitation.changes.length) {
send(res, 409, 'Invitation already redeemed')
} else {
send(res, 200, invitation.changes[0].new_val)
}
}
const assert = async (req, res) => {
const { hash } = req.params
let invitation
await rethinkDB.table('invitations')
.getAll(hash, { index: 'hash' })
.coerceTo('array')
.run(rethinkDBConnection, (err, result) => {
if (err) throw err
invitation = result
})
if (!invitation.length) {
send(res, 404)
} else {
send(res, 200)
}
}
const notfound = (req, res) =>
send(res, 404, 'Route not found')
module.exports = router(
post('/create', create),
get('/:hash', redeem),
head('/:hash', assert),
get('/*', notfound)
)