UNPKG

@eventstore.net/event.store

Version:

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

103 lines 3.57 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const _ = require("lodash"); const mongodb_1 = require("mongodb"); /** * A Persistence Provider that handle all the data in mongodb. */ class MongoProvider { constructor(url) { this.mongoURL = url; } async addEvent(stream, data, type = '') { const events = await this.events(); const sequence = await this.getNextSequenceValue(this.getKey(stream.aggregation, stream.id)) - 1; const commitTimestamp = new Date().getTime(); const event = { commitTimestamp: commitTimestamp, payload: data, sequence: sequence, type: type }; const result = await events.insertOne(_.merge(event, { stream: stream })); if (!result.result.ok) { throw new Error('Error saving event into the store'); } return event; } async getEvents(stream, offset = 0, limit = 0) { const events = await this.events(); const cursor = events.find({ 'stream.id': stream.id, 'stream.aggregation': stream.aggregation }); if (offset > 0) { cursor.skip(offset); } if (limit > 0) { cursor.limit(limit); } return await cursor.toArray(); } async getAggregations(offset = 0, limit = 0) { const events = await this.events(); const cursor = events.aggregate().group({ _id: '$stream.aggregation' }); if (offset > 0) { cursor.skip(offset); } if (limit > 0) { cursor.limit(limit); } const aggregations = await cursor.toArray(); return aggregations; } async getStreams(aggregation, offset = 0, limit = 0) { const events = await this.events(); const cursor = events.aggregate() .match({ 'stream.aggregation': aggregation }) .group({ _id: '$stream.id' }); if (offset > 0) { cursor.skip(offset); } if (limit > 0) { cursor.limit(limit); } const streams = await cursor.toArray(); return streams; } getKey(aggregation, streamId) { return `${aggregation}:${streamId}`; } async events() { if (!this.eventCollection) { const mongoClient = await this.getMongoClient(); this.eventCollection = mongoClient.db().collection('events'); } return this.eventCollection; } async counters() { if (!this.countersCollection) { const mongoClient = await this.getMongoClient(); this.countersCollection = mongoClient.db().collection('counters'); } return this.countersCollection; } async getMongoClient() { if (!this.mongoClient) { this.mongoClient = await mongodb_1.MongoClient.connect(this.mongoURL, { useNewUrlParser: true }); } return this.mongoClient; } async getNextSequenceValue(sequenceName) { const counters = await this.counters(); const result = await counters.findOneAndUpdate({ _id: sequenceName }, // eslint-disable-next-line @typescript-eslint/camelcase { $inc: { sequence_value: 1 } }, { returnOriginal: false, upsert: true }); if (!result.ok) { throw new Error('Error reading next sequence value'); } return result.value.sequence_value; } } exports.MongoProvider = MongoProvider; //# sourceMappingURL=mongo.js.map