-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathroutines.js
117 lines (101 loc) · 2.4 KB
/
routines.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
const { client } = require("./client");
async function getAllRoutines() {
try {
const { rows: routines } = await client.query(`SELECT * FROM routines`);
return await Promise.all(routines.map((all) => getRoutineById(all.id)));
} catch (error) {
throw error;
}
}
async function getPublicRoutines() {
try {
const { rows: public } = await client.query(`
SELECT * FROM routines WHERE public = true;
`);
return await Promise.all(public.map((public) => getRoutineById(public.id)));
} catch (error) {
console.log(error);
throw error;
}
}
async function getAllRoutinesByuser() {
try {
const { rows: allRoutinesByUser } = await client.query(
`SELECT name FROM routines WHERE ;`
);
return allRoutinesByUser;
} catch (error) {
console.error(error);
throw error;
}
}
async function getRoutineById(id) {
try {
const {
rows: [routine],
} = await client.query(`SELECT * FROM routines WHERE id=${id};`);
const { rows: activities } = await client.query(
`SELECT activities.* FROM activities JOIN routine_activities ON "routineId" = ${routine.id} AND "activityId" = activities.id;`
);
routine.activities = activities;
return routine;
} catch (error) {
console.log(error);
throw error;
}
}
async function getPublicRoutinesByUser() {
try {
const { rows: publicRoutines } = await client.query(`
SELECT
`);
} catch (error) {
throw error;
}
}
async function routinesSQL({ id, creatorId, public, name, goal }) {
try {
const {
rows: [routines],
} = await client.query(
`
INSERT INTO routines(id, "creatorId", public, name, goal)
VALUES($1, $2, $3, $4, $5)
RETURNING *;
`,
[id, creatorId, public, name, goal]
);
return routines;
} catch (error) {
throw error;
}
}
async function updateRoutines(id, fields = {}) {
const setString = Object.keys(fields)
.map((key, index) => `"${key}"=$${index + 1}`)
.join(", ");
if (setString.length === 0) {
return;
}
try {
const { rows } = await client.query(
`
UPDATE routines
SET ${setString}
WHERE id=${id}
RETURNING *;
`,
Object.values(fields)
);
return rows;
} catch (error) {
console.error(error);
throw error;
}
}
module.exports = {
routinesSQL,
getAllRoutines,
getPublicRoutines,
updateRoutines,
};