-
Notifications
You must be signed in to change notification settings - Fork 0
/
user-collection.js
85 lines (75 loc) · 2.03 KB
/
user-collection.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
const moment = require('moment')
class UserCollection {
constructor(db, cursor) {
this.db = db
const [reputation, id, timestamp] = cursor || [
Number.MAX_SAFE_INTEGER,
Number.MAX_SAFE_INTEGER,
moment().toISOString(),
]
this.reputation = reputation
this.id = id
this.timestamp = timestamp
this.firstPage = !cursor
}
generateCursor(userPointer) {
const { reputation, id } = userPointer
return [reputation, id, this.timestamp]
}
async popularUsersForward(count = 10) {
const users = await this.db.all(
`
select * from popular_users_forward
where (reputation, id) < (?, ?)
and created_at < ?
and (deleted_at is null or deleted_at > ?)
limit ?
`,
this.reputation,
this.id,
this.timestamp,
this.timestamp,
count + 1
)
const hasNextPage = users.length > count
if (hasNextPage) users.splice(users.length - 1, 1)
return {
afterCursor: hasNextPage && this.generateCursor(users[users.length - 1]),
beforeCursor: !this.firstPage && this.generateCursor(users[0]),
users,
}
}
async popularUsersBackward(count = 10) {
const users = await this.db.all(
`
select * from popular_users_backward
where (reputation, id) > (?, ?)
and created_at < ?
and (deleted_at is null or deleted_at > ?)
limit ?
`,
this.reputation,
this.id,
this.timestamp,
this.timestamp,
count + 1
)
const hasNextPage = users.length > count
if (hasNextPage) users.splice(users.length - 1, 1)
users.reverse()
return {
beforeCursor: hasNextPage && this.generateCursor(users[0]),
afterCursor: users.length && this.generateCursor(users[users.length - 1]),
users,
}
}
async isCollectionStale() {
const result = await this.db.get(
'select id from users where created_at > ? or deleted_at > ? limit 1',
this.timestamp,
this.timestamp
)
return !!result
}
}
module.exports = UserCollection