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
/
getUserChoirs.js
69 lines (62 loc) · 1.59 KB
/
getUserChoirs.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
const Nano = require('nano')
const debug = require('debug')('choirless')
let nano = null
let db = null
// fetch a user by known IP address
// Parameters:
// - userId - the id of the user to fetch
const getUser = async (opts) => {
// connect to db - reuse connection if present
if (!db) {
nano = Nano(process.env.COUCH_URL)
db = nano.db.use(process.env.COUCH_CHOIRLESS_DATABASE)
}
// extract parameters
const userId = opts.userId
if (!userId) {
return {
body: { ok: false, message: 'missing mandatory parameter userId' },
statusCode: 400,
headers: { 'Content-Type': 'application/json' }
}
}
// fetch user from database
let statusCode = 200
let body = null
try {
debug('getUserChoirs', userId)
const query = {
selector: {
userId: userId,
type: 'choirmember'
},
fields: ['choirId']
}
const memberships = await db.find(query)
// load choirs that this user is a member of
const choirIdList = memberships.docs.map((d) => { return d.choirId + ':0' })
let choirs = { rows: [] }
if (choirIdList.length > 0) {
choirs = await db.list({ keys: choirIdList, include_docs: true })
}
body = {
ok: true,
choirs: choirs.rows.map((m) => {
const d = m.doc
delete d._id
delete d._rev
return d
})
}
} catch (e) {
body = { ok: false, message: 'not found' }
statusCode = 404
}
// return API response
return {
body: body,
statusCode: statusCode,
headers: { 'Content-Type': 'application/json' }
}
}
module.exports = getUser