This repository has been archived by the owner on Jan 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
postChoirJoin.js
81 lines (74 loc) · 2.07 KB
/
postChoirJoin.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
const Nano = require('nano')
const debug = require('debug')('choirless')
let nano = null
let db = null
const DB_NAME = process.env.COUCH_CHOIRLESS_DATABASE
// let a user join a choir
// Parameters:
// - `choirId` - choir being joined
// - `userId` - id of user joining
// - `name` - name of user joining.
// - `memberType` - role in choir
const postChoirJoin = async (opts) => {
// connect to db - reuse connection if present
if (!db) {
nano = Nano(process.env.COUCH_URL)
db = nano.db.use(DB_NAME)
}
// extract parameters
const now = new Date()
// check choirType is valid
if (!opts.choirId || !opts.userId || !opts.name || !opts.memberType || !['leader', 'member'].includes(opts.memberType)) {
return {
body: { ok: false, message: 'invalid parameterss' },
statusCode: 400,
headers: { 'Content-Type': 'application/json' }
}
}
const id = opts.choirId + ':member:' + opts.userId
let doc
try {
doc = await db.get(id)
// If we got this far, the user is already a member of the choir.
// If they are of the same member type, we needn't do anything else
if (doc.memberType === opts.memberType) {
return {
body: { ok: false, reason: 'already a member' },
statusCode: 409,
headers: { 'Content-Type': 'application/json' }
}
} else {
// overwrite the member type
doc.memberType = opts.memberType
}
} catch (e) {
// new membership of choir
doc = {
_id: id,
type: 'choirmember',
userId: opts.userId,
choirId: opts.choirId,
name: opts.name,
joined: now.toISOString(),
memberType: opts.memberType
}
}
// write user to database
let statusCode = 200
let body = null
try {
debug('postChoirJoin write ', doc)
const response = await db.insert(doc)
body = { ok: true, choirId: response.id }
} catch (e) {
body = { ok: false }
statusCode = 404
}
// return API response
return {
body: body,
statusCode: statusCode,
headers: { 'Content-Type': 'application/json' }
}
}
module.exports = postChoirJoin