All files / src/provider memory.ts

100% Statements 39/39
88.24% Branches 15/17
100% Functions 7/7
100% Lines 32/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                4x 16x   44x 22x 22x           22x 22x     4x 2x 2x     7x 4x   4x     5x 3x 3x 2x 2x   1x     8x 8x     4x 24x 24x 13x 13x   24x 24x 18x 18x   24x   4x  
import { Event } from '../model/event';
import { Stream } from '../model/stream';
import { PersistenceProvider } from './provider';
 
/**
 * A Persistence Provider that handle all the data in memory. It is a very simple implementation that should be used
 * only for development and test purposes.
 */
export class InMemoryProvider implements PersistenceProvider {
    private store: Map<string, Map<string, Array<Event>>> = new Map();
 
    public async addEvent(stream: Stream, data: any, type = '') {
        const currentEvents = await this.getEventsList(stream.aggregation, stream.id);
        const event: Event = {
            commitTimestamp: new Date().getTime(),
            eventType: type,
            payload: data,
            sequence: currentEvents.length,
        };
        currentEvents.push(event);
        return event;
    }
 
    public async getEvents(stream: Stream, offset = 0, limit?: number) {
        const history = this.getEventsList(stream.aggregation, stream.id);
        return this.take(history.slice(offset), limit || history.length);
    }
 
    public async getAggregations(offset = 0, limit?: number): Promise<Array<string>> {
        const keys = Array.from(this.store.keys());
 
        return this.take(keys.sort().slice(offset), (limit || this.store.size));
    }
 
    public async getStreams(aggregation: string, offset = 0, limit?: number): Promise<Array<string>> {
        const streams = this.store.get(aggregation);
        if (streams) {
            const keys = Array.from(streams.keys());
            return this.take(keys.sort().slice(offset), limit || this.store.size);
        }
        return [];
    }
 
    private take(array: Array<any>, In: number = 1) {
        return array.slice(0, n < 0 ? 0 : n);
    }
 
    private getEventsList(aggregation: string, streamId: string) {
        let streams = this.store.get(aggregation);
        if (!streams) {
            streams = new Map<string, Array<Event>>();
            this.store.set(aggregation, streams);
        }
        let history = streams.get(streamId);
        if (!history) {
            history = new Array<Event>();
            streams.set(streamId, history);
        }
        return history;
    }
}