-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
91 lines (72 loc) · 2.33 KB
/
index.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
/* eslint-disable import/no-extraneous-dependencies */
import RecordModel from 'abgp-js/dist/consensus/models/RecordModel';
import { IRecord, IState, IStorageInterface } from 'abgp-js/dist/consensus/interfaces/IStorageInterface';
import StateModel from 'abgp-js/dist/consensus/models/StateModel';
class PlainStorageRecord implements IRecord {
private readonly db: Map<string, RecordModel>;
public constructor() {
this.db = new Map<string, RecordModel>();
}
async get(hash: string): Promise<RecordModel | null> {
const item = this.db.get(hash);
if (!item) {
return null;
}
return item.cloneObject();
}
async save(record: RecordModel): Promise<void> {
this.db.set(record.hash, record.cloneObject());
}
async has(hash: string): Promise<boolean> {
return this.db.has(hash);
}
async getByTimestamp(timestamp: number): Promise<RecordModel[]> {
return [...this.db.values()]
.filter((v) => v.timestamp === timestamp)
.map((item) => item.cloneObject());
}
async getAfterTimestamp(timestamp: number, timestampIndex: number, limit: number): Promise<RecordModel[]> {
return [...this.db.values()]
.filter((v) =>
v.timestamp > timestamp ||
(v.timestamp === timestamp && v.timestampIndex > timestampIndex))
.sort((a, b) =>
((a.timestamp > b.timestamp ||
(a.timestamp === b.timestamp && a.timestampIndex > b.timestampIndex)
) ? 1 : -1))
.slice(0, limit)
.map((item) => item.cloneObject());
}
async del(hash: string): Promise<void> {
this.db.delete(hash);
}
}
class PlainStorageState implements IState {
private readonly db: Map<string, StateModel>;
public constructor() {
this.db = new Map<string, StateModel>();
}
async get(publicKey: string): Promise<StateModel> {
const state = this.db.get(publicKey);
if (!state) {
return {
timestamp: 0,
timestampIndex: -1,
root: '0',
publicKey
};
}
return state;
}
async save(state: StateModel): Promise<void> {
this.db.set(state.publicKey, state);
}
}
export default class PlainStorage implements IStorageInterface {
public readonly Record: IRecord;
public readonly State: IState;
public constructor() {
this.Record = new PlainStorageRecord();
this.State = new PlainStorageState();
}
}