-
-
Notifications
You must be signed in to change notification settings - Fork 768
/
Copy pathfavorite-projects-store.ts
96 lines (80 loc) · 2.59 KB
/
favorite-projects-store.ts
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
import type EventEmitter from 'events';
import type { Logger, LogProvider } from '../logger';
import type { IFavoriteProject } from '../types/favorites';
import type {
IFavoriteProjectKey,
IFavoriteProjectsStore,
} from '../types/stores/favorite-projects';
import type { Db } from './db';
const T = {
FAVORITE_PROJECTS: 'favorite_projects',
};
interface IFavoriteProjectRow {
user_id: number;
project: string;
created_at: Date;
}
const rowToFavorite = (row: IFavoriteProjectRow) => {
return {
userId: row.user_id,
project: row.project,
createdAt: row.created_at,
};
};
export class FavoriteProjectsStore implements IFavoriteProjectsStore {
private logger: Logger;
private eventBus: EventEmitter;
private db: Db;
constructor(db: Db, eventBus: EventEmitter, getLogger: LogProvider) {
this.db = db;
this.eventBus = eventBus;
this.logger = getLogger('lib/db/favorites-store.ts');
}
async addFavoriteProject({
userId,
project,
}: IFavoriteProjectKey): Promise<IFavoriteProject> {
const insertedProject = await this.db<IFavoriteProjectRow>(
T.FAVORITE_PROJECTS,
)
.insert({ project, user_id: userId })
.onConflict(['user_id', 'project'])
.merge()
.returning('*');
return rowToFavorite(insertedProject[0]);
}
async delete({ userId, project }: IFavoriteProjectKey): Promise<void> {
return this.db(T.FAVORITE_PROJECTS)
.where({ project, user_id: userId })
.del();
}
async deleteAll(): Promise<void> {
await this.db(T.FAVORITE_PROJECTS).del();
}
destroy(): void {}
async exists({ userId, project }: IFavoriteProjectKey): Promise<boolean> {
const result = await this.db.raw(
`SELECT EXISTS(SELECT 1 FROM ${T.FAVORITE_PROJECTS} WHERE user_id = ? AND project = ?) AS present`,
[userId, project],
);
const { present } = result.rows[0];
return present;
}
async get({
userId,
project,
}: IFavoriteProjectKey): Promise<IFavoriteProject> {
const favorite = await this.db
.table<IFavoriteProjectRow>(T.FAVORITE_PROJECTS)
.select()
.where({ project, user_id: userId })
.first();
return rowToFavorite(favorite);
}
async getAll(): Promise<IFavoriteProject[]> {
const groups = await this.db<IFavoriteProjectRow>(
T.FAVORITE_PROJECTS,
).select();
return groups.map(rowToFavorite);
}
}