-
Notifications
You must be signed in to change notification settings - Fork 0
/
moodify-db.js
82 lines (73 loc) · 1.56 KB
/
moodify-db.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
const pgp = require('pg-promise')();
class MoodifyDatabase {
constructor(name) {
const connectionString =
process.env.DATABASE_URL || `postgres://localhost:5432/${name}`;
this.db = pgp(connectionString);
}
dbConnectionCheck = () => {
console.log('Testing database connection...');
return this.getMoodsCount().then((count) =>
console.log(`Found ${count} moods.`)
);
};
getMoodsCount = () => {
return this.db.one('SELECT count(*) FROM moods').then((m) => m.count);
};
getAllMoods = () => {
return this.db.any(
`SELECT
m.id,
m.name,
m.blurb,
m.avatar,
m.color,
m.accent,
m.trim,
m.taccent
FROM moods m`
);
};
getAffirmationByMood = (mood) => {
return this.db.any(
`SELECT
a.id,
a.affirmation,
a.mood_id,
m.name
FROM affirmations a
INNER JOIN moods m on m.id = a.mood_id
WHERE name = $1`,
mood
);
};
getAffirmationById = (id) => {
return this.db.one(
`SELECT *
FROM affirmations
WHERE id = $1`,
id
);
};
// look up memoization
// subquery ?
addAffirmation = ({ affirmation, mood }) => {
return this.db.one(
`INSERT INTO affirmations
(affirmation, mood_id)
VALUES ($1, $2)
RETURNING *`,
[affirmation, mood]
);
};
deleteAffirmation = (id) => {
return this.db.result(
`DELETE
FROM affirmations
WHERE id = $1`,
id,
(a) => a.rowCount
);
};
}
module.exports = MoodifyDatabase;