UNPKG

@eventstore.net/event.store

Version:

A simple and fast EventStore that support multiple persistence and notification providers

77 lines 3.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const mysql_1 = require("./mysql/mysql"); /** * A Persistence Provider that handle all the data in mysql. */ class MySQLProvider { constructor(config) { this.initialized = false; this.mysql = new mysql_1.MySQL(config); } async addEvent(stream, data, type = '') { await this.ensureTables(); let result = await this.mysql.query('INSERT INTO events(streamId, aggregation, payload, type, sequence) ' + 'SELECT ?,?,?,?,COUNT(*) FROM events ' + 'WHERE streamId = ? AND aggregation = ?', [stream.id, stream.aggregation, JSON.stringify(data), type, stream.id, stream.aggregation]); result = await this.mysql.query('SELECT sequence, commitTimestamp FROM events WHERE id=?', [result.insertId]); const event = { commitTimestamp: result.commitTimestamp, payload: data, sequence: result.sequence, type: type }; return event; } async getEvents(stream, offset = 0, limit = -1) { await this.ensureTables(); if (limit <= 0) { limit = Number.MAX_SAFE_INTEGER; } const result = await this.mysql.query('SELECT * FROM events WHERE streamId=? AND aggregation=? LIMIT ?,?', [stream.id, stream.aggregation, offset, limit]); return result.map(data => { return { commitTimestamp: data.commitTimestamp, payload: JSON.parse(data.payload), sequence: data.sequence, type: data.type }; }); } async getAggregations(offset = 0, limit = -1) { await this.ensureTables(); if (limit <= 0) { limit = Number.MAX_SAFE_INTEGER; } return await this.mysql.query('SELECT DISTINCT aggregation FROM events LIMIT ?,?', [offset, limit]); } async getStreams(aggregation, offset = 0, limit = -1) { await this.ensureTables(); if (limit <= 0) { limit = Number.MAX_SAFE_INTEGER; } return await this.mysql.query('SELECT DISTINCT streamId FROM events WHERE aggregation = ? LIMIT ?,?', [aggregation, offset, limit]); } async ensureTables() { if (!this.initialized) { await this.createTables(); this.initialized = true; } } async createTables() { await this.mysql.query('CREATE TABLE IF NOT EXISTS events (' + 'id BIGINT NOT NULL AUTO_INCREMENT,' + 'streamId VARCHAR(40) NOT NULL,' + 'aggregation VARCHAR(40) NOT NULL,' + 'payload TEXT,' + 'type VARCHAR(40),' + 'sequence INT,' + 'commitTimestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,' + 'PRIMARY KEY (id),' + 'INDEX AGGREGATION_INDEX(aggregation),' + 'INDEX STREAM_ID_INDEX(streamId)' + ')'); } } exports.MySQLProvider = MySQLProvider; //# sourceMappingURL=mysql.js.map