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
/
Copy pathpostChoirSongPartName.js
81 lines (72 loc) · 2.11 KB
/
postChoirSongPartName.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')
const kuuid = require('kuuid')
let nano = null
let db = null
const DB_NAME = process.env.COUCH_CHOIRLESS_DATABASE
// create/edit a choir's song
// Parameters:
// - `choirId` - the id of the choir (required)
// - `songId` - the id of the song (required)
// - `partNameId` - the id of the song partName - if matches existing partNameId, that object will be updated, otherwise - new array element will be added
// - `name` - the name of the part (required)
const postChoirSongPartName = async (opts) => {
// connect to db - reuse connection if present
if (!db) {
nano = Nano(process.env.COUCH_URL)
db = nano.db.use(DB_NAME)
}
// check for mandatory parameters
if (!opts.choirId || !opts.songId || !opts.name) {
return {
body: { ok: false, message: 'missing mandatory parameters' },
statusCode: 400,
headers: { 'Content-Type': 'application/json' }
}
}
// load song
let doc
try {
debug('postChoirSongPartName fetch song', opts.choirId, opts.songId)
doc = await db.get(opts.choirId + ':song:' + opts.songId)
} catch (e) {
return {
body: { ok: false, message: 'song not found' },
statusCode: 404,
headers: { 'Content-Type': 'application/json' }
}
}
// see if partNameId is present in partNames
let index = doc.partNames.length // add to end of array
if (!opts.partNameId) {
opts.partNameId = kuuid.id()
} else {
for (let i = 0; i < doc.partNames.length; i++) {
if (doc.partNames[i].partNameId === opts.partNameId) {
index = i
}
}
}
doc.partNames[index] = {
partNameId: opts.partNameId,
name: opts.name
}
// write user to database
let statusCode = 200
let body = null
try {
debug('postChoirSongPartName write song', doc)
await db.insert(doc)
body = { ok: true, songId: opts.songId }
} catch (e) {
body = { ok: false }
statusCode = 404
}
// return API response
return {
body: body,
statusCode: statusCode,
headers: { 'Content-Type': 'application/json' }
}
}
module.exports = postChoirSongPartName