-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathactions.js
More file actions
64 lines (56 loc) · 1.74 KB
/
actions.js
File metadata and controls
64 lines (56 loc) · 1.74 KB
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
const sql = require('./database/queries.js')
function getAllContactsAndTheirGroups() {
return sql.allContacts()
.then((contacts) => {
return Promise.all(contacts.map((contact) => {
return sql.groupsForContact(contact.id)
.then((groups) => {
contact.groups = groups.map(g => g.name)
return contact
})
}))
})
}
function getContactAndTheirGroups(contactID) {
return sql.getContactByID(contactID)
.then((contact) => {
return sql.groupsForContact(contact.id)
.then((groups) => {
contact.groups = groups.map(g => g.name)
return contact
})
})
}
function createContactWithGroups(contactInfo, groups) {
if (!contactInfo.name) throw "Contact must have a name"
if (!contactInfo.email) throw "Contact must have a email"
return sql.createContact(contactInfo)
.then((contact) => {
const contactID = contact.id
return Promise.all(groups.map((groupName) => {
return sql.findOrCreateGroupByName(groupName)
}))
.then((groupRecords) => {
return Promise.all(groupRecords.map((group) => {
const groupID = group.id
return sql.addContactToGroup({contactID, groupID})
}))
})
.then(() => contactID)
})
}
function deleteContactAndTheirMemberships(contactID) {
return sql.deleteMembershipsForContact(contactID)
.then(() => sql.deleteContact(contactID))
}
function deleteGroupAndTheirMemberships(groupID) {
return sql.deleteMembershipsForGroup(groupID)
.then(() => sql.deleteGroup(groupID))
}
module.exports = {
getAllContactsAndTheirGroups,
getContactAndTheirGroups,
createContactWithGroups,
deleteContactAndTheirMemberships,
deleteGroupAndTheirMemberships,
}