-
-
Notifications
You must be signed in to change notification settings - Fork 768
/
Copy pathfavorite-features-store.ts
94 lines (78 loc) · 2.61 KB
/
favorite-features-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
import type EventEmitter from 'events';
import type { IFavoriteFeaturesStore } from '../types';
import type { Logger, LogProvider } from '../logger';
import type { IFavoriteFeatureKey } from '../types/stores/favorite-features';
import type { IFavoriteFeature } from '../types/favorites';
import type { Db } from './db';
const T = {
FAVORITE_FEATURES: 'favorite_features',
};
interface IFavoriteFeatureRow {
user_id: number;
feature: string;
created_at: Date;
}
const rowToFavorite = (row: IFavoriteFeatureRow) => {
return {
userId: row.user_id,
feature: row.feature,
createdAt: row.created_at,
};
};
export class FavoriteFeaturesStore implements IFavoriteFeaturesStore {
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 addFavoriteFeature({
userId,
feature,
}: IFavoriteFeatureKey): Promise<IFavoriteFeature> {
const insertedFeature = await this.db<IFavoriteFeatureRow>(
T.FAVORITE_FEATURES,
)
.insert({ feature, user_id: userId })
.onConflict(['user_id', 'feature'])
.merge()
.returning('*');
return rowToFavorite(insertedFeature[0]);
}
async delete({ userId, feature }: IFavoriteFeatureKey): Promise<void> {
return this.db(T.FAVORITE_FEATURES)
.where({ feature, user_id: userId })
.del();
}
async deleteAll(): Promise<void> {
await this.db(T.FAVORITE_FEATURES).del();
}
destroy(): void {}
async exists({ userId, feature }: IFavoriteFeatureKey): Promise<boolean> {
const result = await this.db.raw(
`SELECT EXISTS (SELECT 1 FROM ${T.FAVORITE_FEATURES} WHERE user_id = ? AND feature = ?) AS present`,
[userId, feature],
);
const { present } = result.rows[0];
return present;
}
async get({
userId,
feature,
}: IFavoriteFeatureKey): Promise<IFavoriteFeature> {
const favorite = await this.db
.table<IFavoriteFeatureRow>(T.FAVORITE_FEATURES)
.select()
.where({ feature, user_id: userId })
.first();
return rowToFavorite(favorite);
}
async getAll(): Promise<IFavoriteFeature[]> {
const groups = await this.db<IFavoriteFeatureRow>(
T.FAVORITE_FEATURES,
).select();
return groups.map(rowToFavorite);
}
}