-
Notifications
You must be signed in to change notification settings - Fork 1
/
posts_storage.js
68 lines (57 loc) · 1.95 KB
/
posts_storage.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
import { encodeManyIntegers, decodeManyIntegers } from './intcodec.js';
export class PostsStorage {
constructor(storage) {
this._storage = storage;
this._data = null;
}
async _fetchDataIfNeeded() {
if (this._data !== null)
return;
this._data = new Map();
const entries = await this._storage.read('p');
for (const entry of entries) {
const [userId, ownerId, postId, commentId] = decodeManyIntegers(entry);
let set = this._data.get(userId);
if (set === undefined) {
set = new Set();
this._data.set(userId, set);
}
set.add(`${ownerId},${postId},${commentId}`);
}
}
async getUsers() {
await this._fetchDataIfNeeded();
const keysCopy = [...this._data.keys()];
keysCopy.reverse();
return keysCopy;
}
async getUserPosts(userId) {
await this._fetchDataIfNeeded();
const set = this._data.get(userId);
if (set === undefined)
return [];
const result = [];
for (const setValue of set) {
const [ownerId, postId, commentId] = setValue.split(',').map(x => parseInt(x));
result.push({ownerId: ownerId, postId: postId, commentId: commentId});
}
result.reverse();
return result;
}
async addPost(userId, datum) {
await this._fetchDataIfNeeded();
const setValue = `${datum.ownerId},${datum.postId},${datum.commentId}`;
let set = this._data.get(userId);
if (set === undefined) {
set = new Set();
this._data.set(userId, set);
} else {
if (set.has(setValue))
return false;
}
set.add(setValue);
const entry = encodeManyIntegers([userId, datum.ownerId, datum.postId, datum.commentId]);
await this._storage.write('p', entry);
return true;
}
}