CompositeBackend.js
1.26 KB
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
/**
* CompositeBackend - 组合后端
*
* 将日志同时写入多个后端
*/
const { BaseBackend } = require('./BaseBackend');
class CompositeBackend extends BaseBackend {
constructor(options = {}) {
super({ name: 'composite', ...options });
this.backends = [];
}
/**
* 添加后端
*/
add(backend) {
this.backends.push(backend);
return this;
}
/**
* 移除后端
*/
remove(backend) {
const index = this.backends.indexOf(backend);
if (index > -1) {
this.backends.splice(index, 1);
}
return this;
}
async init() {
await Promise.all(this.backends.map(b => b.init()));
}
async write(entry) {
await Promise.all(this.backends.map(b => b.write(entry)));
}
async writeBatch(entries) {
await Promise.all(this.backends.map(b => b.writeBatch(entries)));
}
async query(filters = {}) {
// 返回第一个支持查询的后端的结果
for (const backend of this.backends) {
try {
const results = await backend.query(filters);
if (results.length > 0) return results;
} catch {
// 继续尝试下一个
}
}
return [];
}
async close() {
await Promise.all(this.backends.map(b => b.close()));
}
}
module.exports = { CompositeBackend };