-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils.js
893 lines (798 loc) · 27.7 KB
/
utils.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
const events = require('events');
const sqlite3 = require("sqlite3").verbose();
const md5 = require('md5');
const util = require('util');
const CronJob = require('cron').CronJob;
class Scheduler {
constructor(trackPeriodInMs = 2 * 1000 * 60) {
this.trackPeriodInMs = trackPeriodInMs;
this.emitter = new events.EventEmitter();
this.emitter.addListener('next', this.next);
}
schedule(handler) {
this.emitter.addListener('perform', handler);
}
start() {
this.next();
}
next = () => {
this.timerId = setTimeout(
() => this.emitter.emit('perform'),
this.trackPeriodInMs
);
}
}
function shortenNumber(n, d) {
if (n < 1) return "0";
var k = n = Math.floor(n);
if (n < 1000) return (n.toString().split("."))[0];
if (d !== 0) d = d || 1;
function shorten(a, b, c) {
var d = a.toString().split(".");
if (!d[1] || b === 0) {
return d[0] + c
} else {
return d[0] + "." + d[1].substring(0, b) + c;
}
}
k = n / 1e15; if (k >= 1) return shorten(k, d, "Q");
k = n / 1e12; if (k >= 1) return shorten(k, d, "T");
k = n / 1e9; if (k >= 1) return shorten(k, d, "B");
k = n / 1e6; if (k >= 1) return shorten(k, d, "M");
k = n / 1e3; if (k >= 1) return shorten(k, d, "K");
}
class DbConnection {
constructor(dbFile = "./.data/sqlite.db") {
this.dbFile = dbFile;
this.isOpen = false;
this.initConnection();
this.resetCallbacks = [];
this.closeCallbacks = [];
}
initConnection() {
this.database = new sqlite3.Database(this.dbFile);
this.database.on('open', () => {
this.isOpen = true;
});
this.database.on('close', () => {
this.isOpen = false;
});
this.asyncClose = util.promisify(this.database.close).bind(this.database);
}
setup() {
this.database.serialize(() => {
this.database.run('PRAGMA journal_mode = WAL;');
this.database.run('PRAGMA auto_vacuum = FULL;');
// this.database.run('PRAGMA recursive_triggers=1;');
this.database.run(`
CREATE TABLE IF NOT EXISTS feedbacks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user TEXT NOT NULL,
text TEXT NOT NULL CHECK (length(text) >= 1 AND length(text) <= 280),
key TEXT NOT NULL,
parent TEXT NOT NULL,
child TEXT NOT NULL,
resolved INTEGER NO NULL DEFAULT 0 CHECK (resolved = 0 OR resolved = 1),
approved INTEGER NO NULL DEFAULT 0 CHECK (resolved = 0 OR resolved = 1),
created TEXT NOT NULL DEFAULT(datetime('now')),
updatedAt TEXT NOT NULL DEFAULT(datetime('now')),
UNIQUE(key)
);
`);
this.database.run(`CREATE INDEX IF NOT EXISTS idx_feedbacks_user_parent_child ON feedbacks(user, parent, child);`);
this.database.run(`CREATE INDEX IF NOT EXISTS idx_feedbacks_resolved ON feedbacks(resolved);`);
this.database.run(`CREATE INDEX IF NOT EXISTS idx_feedbacks_approved ON feedbacks(approved);`);
this.database.run(`CREATE INDEX IF NOT EXISTS idx_feedbacks_created ON feedbacks(created);`);
this.database.run(`
CREATE TRIGGER IF NOT EXISTS [trg_feedbacks_updatedAt]
AFTER UPDATE
ON feedbacks
BEGIN
UPDATE feedbacks SET updatedAt=datetime('now') WHERE id=OLD.id;
END;
`);
this.database.run(`
CREATE TABLE IF NOT EXISTS likes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user TEXT NOT NULL,
parent TEXT NOT NULL,
child TEXT NOT NULL,
type TEXT NOT NULL DEFAULT('like') CHECK (type = 'like' OR type = 'dislike' OR type = 'unknown'),
created TEXT NOT NULL DEFAULT(datetime('now')),
updatedAt TEXT NOT NULL DEFAULT(datetime('now')),
UNIQUE(user, parent, child)
);
`);
this.database.run(`
CREATE TRIGGER IF NOT EXISTS [trg_likes_updatedAt]
AFTER UPDATE
ON likes
BEGIN
UPDATE likes SET updatedAt=datetime('now') WHERE id=OLD.id;
END;
`);
this.database.run(`CREATE INDEX IF NOT EXISTS idx_likes_parent_child ON likes(parent, child);`);
this.database.run(`CREATE INDEX IF NOT EXISTS idx_likes_created ON likes(created);`);
this.database.run(`
CREATE TABLE IF NOT EXISTS counters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT NOT NULL,
count INTEGER NOT NULL DEFAULT(0),
created TEXT NOT NULL DEFAULT(date('now')),
updatedAt TEXT NOT NULL DEFAULT(datetime('now')),
UNIQUE(key, created)
);
`);
this.database.run(`
CREATE TRIGGER IF NOT EXISTS [trg_counters_updatedAt]
AFTER UPDATE
ON counters
BEGIN
UPDATE counters SET updatedAt=datetime('now') WHERE id=OLD.id;
END;
`);
this.database.run(`
CREATE TABLE IF NOT EXISTS history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
child TEXT NOT NULL,
parent TEXT NOT NULL,
canInclude INTEGER NOT NULL DEFAULT('no') CHECK (canInclude = 'yes' OR canInclude = 'no' OR canInclude = 'doubt'),
count INTEGER NOT NULL DEFAULT(0),
created TEXT NOT NULL DEFAULT(date('now')),
updatedAt TEXT NOT NULL DEFAULT(datetime('now')),
UNIQUE(child, parent, canInclude, created)
);
`);
this.database.run(`
CREATE TRIGGER IF NOT EXISTS [trg_history_updatedAt]
AFTER UPDATE
ON history
BEGIN
UPDATE history SET updatedAt=datetime('now') WHERE id=OLD.id;
END;
`);
this.database.run(`CREATE INDEX IF NOT EXISTS idx_history_created ON history(created);`);
this.database.run(`CREATE INDEX IF NOT EXISTS idx_history_count ON history(count);`);
this.database.run(`CREATE INDEX IF NOT EXISTS idx_history_child_parent_created ON history(child, parent, created);`);
this.database.run(`CREATE INDEX IF NOT EXISTS idx_history_updatedAt ON history(updatedAt);`);
this.database.run(`
CREATE TABLE IF NOT EXISTS invites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT NOT NULL,
user TEXT NULL,
role TEXT NOT NULL,
used INTEGER NOT NULL DEFAULT(0) CHECK (used = 0 OR used = 1),
created TEXT NOT NULL DEFAULT(date('now')),
updatedAt TEXT NOT NULL DEFAULT(datetime('now')),
UNIQUE(key, role)
);
`);
this.database.run(`CREATE INDEX IF NOT EXISTS idx_invites_used ON invites(used);`);
this.database.run(`
CREATE TRIGGER IF NOT EXISTS [trg_invites_updatedAt]
AFTER UPDATE
ON invites
BEGIN
UPDATE invites SET updatedAt=datetime('now') WHERE id=OLD.id;
END;
`);
});
}
set onUpdate (cb) {
this.resetCallbacks.push(cb);
}
set onClose(cb) {
this.closeCallbacks.push(cb);
}
callResetCallbacks() {
if (this.resetCallbacks.length) {
this.resetCallbacks.map(cb => typeof cb === 'function' && cb())
}
}
callCloseCallbacks() {
if (this.closeCallbacks.length) {
this.closeCallbacks.map(cb => typeof cb === 'function' && cb())
}
}
async close() {
if (this.isOpen) {
await this.asyncClose();
}
this.callCloseCallbacks();
}
async reset() {
if(this.isOpen) {
await this.close();
this.database = new sqlite3.Database(this.dbFile);
this.initConnection();
this.setup();
this.callResetCallbacks();
}
}
}
class DbManager {
constructor(conn) {
this.conn = conn;
this.conn.onUpdate = () => {
this.bindMethods();
};
this.bindMethods();
}
bindMethods() {
this.getAsync = util.promisify(this.db.get).bind(this.db);
this.allAsync = util.promisify(this.db.all).bind(this.db);
this.runAsync = util.promisify(this.db.run).bind(this.db);
}
get db() {
return this.conn.database;
}
runOneByOne(cb) {
this.db.serialize(cb);
}
}
class DailyFeedbackExceededError extends Error {
constructor() {
super('FEEDBACK limit exceeded');
}
}
class FeedbackManager extends DbManager {
canAddFeedback(limit=5) {
return new Promise((resolve, reject) => {
if (limit === 0) reject(new DailyFeedbackExceededError());
this.db.get(
`SELECT COUNT(id) as count FROM feedbacks WHERE date(created)=?`,
[new Date().toISOString().substring(0, 10)],
(err, row) => {
if (err) {
return reject(err);
}
if (row.count < limit) {
resolve(true);
} else {
reject(new DailyFeedbackExceededError());
}
});
});
}
countByTags({ parent, child }) {
return new Promise((resolve, reject) => {
this.db.get(
`SELECT COUNT(id) as count
FROM feedbacks WHERE
parent=? AND
child=?;`,
[parent, child],
(err, row) => {
if (err) {
return reject(err);
}
resolve(shortenNumber(row.count));
}
);
});
}
countAll() {
return new Promise((resolve, reject) => {
this.db.get(`SELECT COUNT(id) as count FROM feedbacks;`, [], (err, row) => {
if (err) {
return reject(err);
}
return resolve(shortenNumber(row.count));
});
});
}
add({ user, text, parent, child }) {
return new Promise((resolve, reject) => {
const pairKey = `${parent}:${child}`;
const key = md5(`${user}:${text}:${pairKey}`);
this.db.run(`INSERT INTO feedbacks (user, key, parent, child, text) VALUES (?,?,?,?,?);`, [user, key, parent, child, text], function (err) {
if (err) {
return reject(err);
}
resolve(this.changes);
});
});
}
getLastFeedbacks({ user, parent, child }) {
return new Promise((resolve, reject) => {
this.db.all(`
SELECT * FROM feedbacks WHERE
user=? AND
parent=? AND
child=?
ORDER BY created DESC
LIMIT 10`,
[user, parent, child],
function (err, rows) {
if (err) {
return reject(err);
}
resolve(rows);
}
);
});
}
approve({ id }) {
return this.runAsync(`UPDATE feedbacks SET approved=1 WHERE id=?`, [id]);
}
unapprove({ id }) {
return this.runAsync(`UPDATE feedbacks SET approved=0 WHERE id=?`, [id]);
}
resolve({ id }) {
return this.runAsync(`UPDATE feedbacks SET resolved=1 WHERE id=?`, [id]);
}
unresolve({ id }) {
return this.runAsync(`UPDATE feedbacks SET resolved=0 WHERE id=?`, [id]);
}
remove({ id }) {
return this.runAsync(`DELETE FROM feedbacks WHERE id=?`, [id]);
}
async getAllByPage({ page }) {
const row = await this.getAsync('SELECT COUNT(id) as count FROM feedbacks;', []);
const count = row.count || 0;
const MaxPages = Math.floor(count / 10) + (count % 10 !== 0 ? 1 : 0);
const offset = ((page - 1) * 10) % (count || 1);
const rows = await this.allAsync(`SELECT * FROM feedbacks ORDER BY created DESC LIMIT 10 OFFSET ${offset};`, []);
return { currentPage: page, feedbacks: rows, totalPages: MaxPages };
}
}
class RecordNotFoundError extends Error {
constructor(message) {
super(message || 'Record not found');
}
}
class LikesManager extends DbManager {
getCount(parent, child, type='like') {
return new Promise((resolve, reject) => {
this.db.get(`SELECT COUNT(id) as count FROM likes WHERE parent=? AND child=? AND type=?`, [parent, child, type], function (err, row) {
if (err) {
return reject(err);
}
resolve(row && row.count || 0);
});
});
}
getLike(user, parent, child) {
return new Promise((resolve, reject) => {
this.db.get(`SELECT id, type FROM likes WHERE user=? AND parent=? AND child=?`, [user, parent, child], function (err, row) {
if (err) {
return reject(err);
}
if (!row) {
return reject(new RecordNotFoundError());
}
resolve(row);
});
});
}
async getLikeSafe(user, parent, child, defaultValue = {}) {
try {
return await this.getLike(user, parent, child);
} catch(e) {
if (typeof e === RecordNotFoundError) {
return defaultValue;
}
}
}
createLike(user, parent, child, type='like') {
return new Promise((resolve, reject) => {
this.db.run(`INSERT INTO likes(user, parent, child, type) VALUES(?,?,?,?)`, [user, parent, child, type], function (err) {
if (err) {
return reject(err);
}
resolve(this.lastID);
});
});
}
updateLike(id, type = 'like') {
return new Promise((resolve, reject) => {
this.db.get(`UPDATE likes SET type=? WHERE id=?`, [type, id], function (err) {
if (err) {
return reject(err);
}
resolve(this.changes);
});
});
}
async like(user, parent, child, type='like') {
try {
const { id } = await this.getLike(user, parent, child);
await this.updateLike(id, type);
} catch (e) {
await this.createLike(user, parent, child, type);
}
}
async unlike(user, parent, child) {
return this.like(user, parent, child, 'unknown');
}
async dislike(user, parent, child) {
return this.like(user, parent, child, 'dislike');
}
async undislike(user, parent, child) {
return this.like(user, parent, child, 'unknown');
}
async votes(user, parent, child) {
const likes = await this.getCount(parent, child, 'like');
const dislikes = await this.getCount(parent, child, 'dislike');
const like = await this.getLikeSafe(user, parent, child, { type: 'unknown' });
return {
likes: shortenNumber(likes),
dislikes: shortenNumber(dislikes),
disliked: like && like.type === 'dislike' || false,
liked: like && like.type === 'like' || false,
user
};
}
}
class Counter extends DbManager {
constructor(dbConn) {
super(dbConn);
this.totalCount = 0;
this.uniqTotalCount = 0;
}
get count() {
return this.totalCount;
}
get uniqCount() {
return this.uniqTotalCount;
}
async getBy({ key, date }) {
return new Promise((resolve, reject) => {
this.db.get(
'SELECT key, count FROM counters WHERE key=? AND created=?',
[key, date.toISOString().slice(0,10)],
function (err, row) {
if (err) {
return reject(err);
}
if (!row) {
return reject(new RecordNotFoundError());
}
resolve(row);
});
});
}
async create({ key }) {
return new Promise((resolve, reject) => {
this.db.run('INSERT INTO counters(key, count) VALUES(?,?)', [key, 1], function (err) {
if (err) {
return reject(err);
}
resolve(this.lastID);
});
});
}
async update({ key }) {
return new Promise((resolve, reject) => {
this.db.run(
'UPDATE counters SET count=count+1 WHERE key=? AND created=?',
[
key,
new Date().toISOString().slice(0, 10)
],
function (err) {
if (err) {
return reject(err);
}
resolve(this.lastID);
});
});
}
async getTotals() {
return new Promise((resolve, reject) => {
this.db.get(
'SELECT COUNT(id) as uniqCount, SUM(count) as totalCount FROM counters WHERE created=? GROUP BY date(created)',
[new Date().toISOString().slice(0, 10)],
function (err, row) {
if (err) {
return reject(err);
}
if (!row) {
resolve({ uniqCount: 0, totalCount: 0 });
}
resolve(row);
});
});
}
async register(ip) {
const key = md5(ip);
try {
const record = await this.getBy({ key, date: new Date() });
await this.update({ key: record.key });
} catch (e) {
if (e instanceof RecordNotFoundError) {
await this.create({ key });
}
}
}
async load() {
const result = await this.getTotals();
this.totalCount = result && result.totalCount || 0;
this.uniqTotalCount = result && result.uniqCount || 0;
}
}
class HistoryManager extends DbManager {
async getBy({ parent, child, date }) {
return new Promise((resolve, reject) => {
this.db.get(
'SELECT id, parent, child, canInclude FROM history WHERE parent=? AND child=? AND created=?',
[parent, child, date.toISOString().slice(0, 10)],
function (err, row) {
if (err) {
return reject(err);
}
if (!row) {
return reject(new RecordNotFoundError());
}
resolve(row);
});
});
}
async getLastBy() {
return new Promise((resolve, reject) => {
this.db.all(
`SELECT id, parent, child, canInclude, count FROM history ORDER BY updatedAt DESC LIMIT 10`,
[],
function (err, rows) {
if (err) {
return reject(err);
}
resolve(rows);
});
});
}
async create({ parent, child, canInclude}) {
return new Promise((resolve, reject) => {
this.db.run(
'INSERT INTO history(parent, child, canInclude, count) VALUES(?,?,?,1)',
[parent, child, canInclude.toLowerCase()],
function (err) {
if (err) {
return reject(err);
}
resolve(this.lastID);
});
});
}
async updateCountBy({ parent, child, date }) {
return new Promise((resolve, reject) => {
this.db.run(
'UPDATE history SET count=count+1 WHERE parent=? AND child=? AND created=?',
[
parent,
child,
date.toISOString().slice(0, 10)
],
function (err) {
if (err) {
return reject(err);
}
resolve(this.lastID);
});
});
}
async register({ parent, child, canInclude }) {
try {
const date = new Date();
const record = await this.getBy({ parent, child, date });
await this.updateCountBy({ parent: record.parent, child: record.child, date });
} catch (e) {
if (e instanceof RecordNotFoundError) {
await this.create({ parent, child, canInclude });
}
}
}
}
class InvitesManager extends DbManager {
async apply({ key, user }) {
const result = await this.getAsync(`SELECT id FROM invites WHERE key=? AND used=0`, [key]);
if (!result) {
throw new RecordNotFoundError();
}
await this.runAsync(`UPDATE invites SET user=?, used=1 WHERE key=?`, [user, key]);
return this.getAsync(`SELECT * FROM invites WHERE key=? AND used=1`, [key]);
}
}
class StatManager extends DbManager {
constructor(conn) {
super(conn);
this.cacheKey = null;
this.maxUniqCount = 0;
this.cacheValues = null;
}
get totalCount() {
return this.maxUniqCount;
}
async getStatCountersFor2Weeks() {
const shortDateNow = new Date().toISOString().substring(0, 10);
if (this.cacheKey !== shortDateNow) {
this.cacheKey = shortDateNow;
const { maximum } = await this.getAsync('SELECT MAX(count) as maximum from (SELECT COUNT(id) as count FROM counters c2 GROUP BY c2.created)');
this.maxUniqCount = maximum;
this.cacheValues = await this.allAsync(`SELECT curr.count as nowCount, prev.count as prevCount, curr.dayofweek FROM
(SELECT COUNT(id) as count, c2.created,
case cast (strftime('%w', c2.created) as integer)
when 0 then 'Su'
when 1 then 'Mo'
when 2 then 'Tu'
when 3 then 'We'
when 4 then 'Th'
when 5 then 'Fr'
else 'Sa'
end as dayofweek
FROM counters c2
WHERE c2.created >= date('${shortDateNow}', '-13 days')
AND c2.created <= date('${shortDateNow}', '-7 days')
GROUP BY c2.created ORDER BY c2.created) as prev
LEFT JOIN
(SELECT COUNT(id) as count, c2.created,
case cast (strftime('%w', c2.created) as integer)
when 0 then 'Su'
when 1 then 'Mo'
when 2 then 'Tu'
when 3 then 'We'
when 4 then 'Th'
when 5 then 'Fr'
else 'Sa'
end as dayofweek
FROM counters c2
WHERE c2.created >= date('${shortDateNow}', '-6 days')
AND c2.created <= '${shortDateNow}'
GROUP BY c2.created ORDER BY c2.created) as curr
ON curr.dayofweek = prev.dayofweek`
);
}
return Promise.resolve(this.cacheValues);
}
}
function getBarCssByValues(left, right, total) {
const leftValue = Number(left);
const rightValue = Number(right);
const isLower = leftValue < rightValue;
const heightInPercent = Number(((leftValue * 100) / total).toFixed(2));
const zIndex = isLower ? 2 : 1;
return {
zIndex,
heightInPercent
}
}
class CronDbManager extends DbManager {
startCronJob({ cronTime, onTick, ...otherConfigProps }) {
if (!this.cron) {
this.cron = new CronJob({ cronTime, onTick, runOnInit: true, ...otherConfigProps });
this.cron.start();
}
}
stopCronJob() {
if (this.cron) {
this.cron.stop();
this.cron = null;
}
}
}
class BaseCronDbManager extends CronDbManager {
constructor(conn) {
super(conn);
this.conn.onUpdate = () => this.restart();
this.conn.onClose = () => this.stop();
this.cache = {};
}
setCronTime(value) {
this.cronTime = value;
}
start() {
this.startCronJob({
cronTime: this.cronTime,
onTick: () => {
this.cache = {};
}
});
}
stop() {
this.stopCronJob();
}
restart() {
this.stop();
this.start();
}
hasKey(cacheKey) {
return typeof this.cache[cacheKey] !== 'undefined';
}
getByKey(cacheKey) {
return this.cache[cacheKey];
}
setByKey(cacheKey, value) {
this.cache[cacheKey] = value;
}
}
class SimpleRecommendManager extends BaseCronDbManager {
constructor(conn) {
super(conn);
this.setCronTime(process.env.RECOMMEND_CLEAR_CACHE_CRON_TIME || '0 */30 * * * *');
}
async getFromCacheOrQuery(childTagName, parentTagName) {
const cacheKey = `${childTagName}${parentTagName}`;
if (this.hasKey(cacheKey)) {
return this.getByKey();
}
const record = await this.getAsync(`
select child, parent, count, (julianday('now') - julianday(created)) / 365 as attenuation_factor
from history
where child=? order by attenuation_factor ASC, count DESC LIMIT 1`,
[parentTagName]);
this.setByKey(cacheKey, record);
return record;
}
}
class StatLikesManager extends BaseCronDbManager {
constructor(conn) {
super(conn);
this.setCronTime(process.env.RECOMMEND_CLEAR_CACHE_CRON_TIME || '0 */30 * * * *');
}
async getMostLiked() {
const cacheKey = 'CACHED_LIKED_RESULT';
if (this.hasKey(cacheKey)) {
return this.getByKey(cacheKey);
}
const records = await this.allAsync(`
select * from (select
parent,
child,
SUM(case type
when 'like' then 1
else 0
end) display,
SUM(case type
when 'dislike' then 1
else 0
end) disliked,
count(id) as count from likes
where type in ('like', 'dislike')
group by parent, child
order by count desc
limit 10) where display > disliked;`);
if (records && records.length) {
this.setByKey(cacheKey, records);
}
return records;
}
async getMostDisliked() {
const cacheKey = 'CACHED_DISLIKED_RESULT';
if (this.hasKey(cacheKey)) {
return this.getByKey(cacheKey);
}
const records = await this.allAsync(`select * from (select
parent,
child,
SUM(case type
when 'like' then 1
else 0
end) liked,
SUM(case type
when 'dislike' then 1
else 0
end) display,
count(id) as count from likes
where type in ('like', 'dislike')
group by parent, child
order by count desc
limit 10) where liked < display;`);
if (records && records.length) {
this.setByKey(cacheKey, records);
}
return records;
}
}
module.exports.StatManager = StatManager;
module.exports.Scheduler = Scheduler;
module.exports.Counter = Counter;
module.exports.shortenNumber = shortenNumber;
module.exports.DbConnection = DbConnection;
module.exports.FeedbackManager = FeedbackManager;
module.exports.LikesManager = LikesManager;
module.exports.HistoryManager = HistoryManager;
module.exports.InvitesManager = InvitesManager;
module.exports.RecordNotFoundError = RecordNotFoundError;
module.exports.getBarCssByValues = getBarCssByValues;
module.exports.SimpleRecommendManager = SimpleRecommendManager;
module.exports.StatLikesManager = StatLikesManager;