CompositeBackend.js 1.26 KB
/**
 * 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 };