This repository was 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 pathpostChoirSong.js
91 lines (85 loc) · 2.43 KB
/
postChoirSong.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
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
// - `userId` - the id of the user adding the song
// - `name` - the name of the song
// - `description` - a description of a song
// - `partNames` - an array of parts e.g. `['alto','tenor','soprano']`
const postChoirSong = 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 choirId = opts.choirId
const now = new Date()
let songId
let doc = {}
// is this a request to edit an existing choir
if (opts.choirId && opts.songId) {
try {
debug('postChoirSong fetch song', choirId)
doc = await db.get(opts.choirId + ':song:' + opts.songId)
doc.name = opts.name ? opts.name : doc.name
doc.description = opts.description ? opts.description : doc.description
songId = opts.songId
} catch (e) {
return {
body: { ok: false, message: 'song not found' },
statusCode: 404,
headers: { 'Content-Type': 'application/json' }
}
}
} else {
if (!opts.choirId || !opts.userId || !opts.name) {
return {
body: { ok: false, message: 'missing mandatory parameters' },
statusCode: 400,
headers: { 'Content-Type': 'application/json' }
}
}
songId = kuuid.id()
let partNames = []
if (opts.partNames) {
partNames = opts.partNames.map((p) => { return { partNameId: kuuid.id(), name: p } })
}
doc = {
_id: opts.choirId + ':song:' + songId,
type: 'song',
songId: songId,
choirId: opts.choirId,
userId: opts.userId,
name: opts.name,
description: opts.description || '',
partNames: partNames,
createdOn: now.toISOString()
}
}
// write user to database
let statusCode = 200
let body = null
try {
debug('postChoirSong write song', doc)
await db.insert(doc)
delete doc._rev
delete doc._id
body = { ok: true, songId: songId, song: doc }
} catch (e) {
body = { ok: false }
statusCode = 404
}
// return API response
return {
body: body,
statusCode: statusCode,
headers: { 'Content-Type': 'application/json' }
}
}
module.exports = postChoirSong