forked from clintonwoo/hackernews-react-graphql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCache.js
100 lines (73 loc) · 2.28 KB
/
Cache.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
// Interface: Commentable (Object can be commented on) comments, commentCount, commenter
// Interface: Voteable (Object can be voted on) upvotes, upvoteCount, hidden, hiddenCount,
// Data Type: Comment, can be on a news item or another comment
// Every time an upvote/downvote/comment is made, update the count
import LRU from 'lru-cache';
import debug from 'debug';
import {
Feed,
} from './Models';
const logger = debug('app:Cache');
logger.log = console.log.bind(console);
// The cache is a singleton
export function warmCache() {
// Fetch the front pages
Feed.getForType('TOP', 30, 0);
Feed.getForType('NEW', 30, 0);
// Run every 15 mins
setTimeout(warmCache, 1000 * 60 * 15);
}
class Cache {
isReady = false;
/* BEGIN NEWS ITEMS */
getNewsItem(id) {
// return this.newsItems.find(newsItem => newsItem.id === id);
return this.newsItemsCache.get(id);
}
setNewsItem(id, newsItem) {
return this.newsItemsCache.set(id, newsItem);
}
/* END NEWS ITEMS */
/* BEGIN USERS */
getUser(id) {
return this.userCache.get(id);
}
getUsers() {
return this.userCache.dump();
}
setUser(id, user) {
logger(`Cache set user ${user}`);
this.userCache.set(id, user);
return user;
}
/* END USERS */
/* BEGIN COMMENTS */
getComment(id) {
return this.commentCache.get(id);
}
setComment(id, comment) {
this.userCache.set(comment.id, comment);
logger(`Cache set comment ${comment}`);
return comment;
}
/* END COMMENTS */
/* BEGIN CACHES */
newNewsItemsCache = LRU({
max: 500,
maxAge: 1000 * 60 * 60, // 60 Minute cache: ms * s * m
})
newsItemsCache = LRU({
max: 1000,
maxAge: 1000 * 60 * 60, // 60 Minute cache: ms * s * m
})
userCache = LRU({
max: 500,
maxAge: 1000 * 60 * 60 * 2, // 2 hour cache: ms * s * m
})
commentCache = LRU({
max: 5000,
maxAge: 1000 * 60 * 60 * 1, // 1 hour cache: ms * s * m
})
/* END CACHES */
}
export default new Cache();