npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cqrs-eventstore

v1.1.1

Published

CQRS and Event Sourcing for Node.js 4+, supporting snapshots, built-in cache, hooks and payload compression

Downloads

8

Readme

CQRS-EventStore

You need Node.js 4+ to use it!

Installation

$ npm install cqrs-eventstore

Working example

A full example is provided in the demo folder. To run it:

  • cd to the demo folder
  • npm install
  • node event-store-demo.js

Domain and DTOs

In order to use CQRS-EventStore, you need to implement your own aggregate and DTOs. Your aggregate must extend Aggregate.

An aggregate example including the DTOs:

"use strict";

class BaseEvent {
    constructor() {
        this.id
        this.version
    }
}

module.exports = BaseEvent
"use strict"

const BaseEvent = require("./baseEvent")

class AddressUpdated extends BaseEvent {
    constructor(address) {
        super()
        this.address = address
    }
}

module.exports = AddressUpdated
"use strict"

const BaseEvent = require("./baseEvent")

class MobileUpdated extends BaseEvent {
    constructor(mobile) {
        super()
        this.mobile = mobile
    }
}

module.exports = MobileUpdated
"use strict"

const BaseEvent = require("./baseEvent")

class UserInfoCreated extends BaseEvent {
    constructor(name, surname, address, mobile) {
        super()
        this.name = name
        this.surname = surname
        this.address = address
        this.mobile = mobile
    }
}

module.exports = UserInfoCreated
"use strict"

const NodeEventStore = require("cqrs-eventstore")
const UserInfoCreated = require("./dto/userInfoCreated")
const AddressUpdated = require("./dto/addressUpdated")
const MobileUpdated = require("./dto/mobileUpdated")
const clone = require("clone") //Clone is used for the snapshot, it's totally up to you how to implement it.

function UserInfo(id) {

    //We are not exposing the UserInfo to the outside world, but we access to it through query.
    function UserInfoObj() {
        this.name
        this.surname
        this.address
        this.mobile
    }
    
    let _userInfo
    
    class UserInfo extends NodeEventStore.Aggregate {
    
        constructor(id) {
            super(id)
            _userInfo = new UserInfoObj()
        }
    
        snapshot() {
            return clone(_userInfo)
        }
    
        applySnapshot(payload) {
            _userInfo = payload
        }
        
        //Queries
        get Mobile() {
            return _userInfo.mobile
        }
    
        get Address() {
            return _userInfo.address
        }
        
        //Mutators
        initialize(name, surname, address, mobile) {
            super.raiseEvent(new UserInfoCreated(name, surname, address, mobile))
        }
    
        updateAddress(address) {
            super.raiseEvent(new AddressUpdated(address))
        }
    
        updateMobile(mobile, hookFn) {
            super.raiseEvent(new MobileUpdated(mobile), hookFn)
        }
        
        //Apply
        UserInfoCreated(payload) {
            _userInfo.name = payload.name
            _userInfo.surname = payload.surname
            _userInfo.address = payload.address
            _userInfo.mobile = payload.mobile
        }
    
        AddressUpdated(payload) {
            _userInfo.address = payload.address
        }
    
        MobileUpdated(payload) {
            _userInfo.mobile = payload.mobile
        }
    }
    
    return new UserInfo(id)
}

module.exports = UserInfo

Implementing the persistence layer

In order to implement your own persistence layer, you need to extend PersistenceAdapter and register it into the configurator (I'll show it later). The methods save, readSnapshot and readEvents must be implemented. All methods must return a promise. In the save method you need to persist your events and snapshot.

Below an example how to implement a sqlite persistor.

"use strict"

const nodeEventStore = require("cqrs-eventstore")
const fs = require("fs");
const sqlite3 = require("sqlite3").verbose();
const _ = require("underscore")
const util = require("util")
const uuid = require("uuid")

class SqlitePersistor extends nodeEventStore.PersistenceAdapter {
	constructor() {
		super()

		const file = "eventStore.db";
		const exists = fs.existsSync(file);
		this.db = new sqlite3.Database(file);

		this.db.serialize(() => {
			if (!exists) {
				this.db.run("CREATE TABLE Events (id TEXT, streamId TEXT, version INTEGER, timestamp TEXT, eventType TEXT, payload BLOB)");
				this.db.run("CREATE TABLE Snapshots (id TEXT, streamId TEXT, version INTEGER, timestamp TEXT, payload BLOB)");
			}
		});
	}

	save(events, snapshots) {
		const self = this;
		return new Promise((resolve, reject) => {
			self.db.serialize(() => {
				try {
					self.db.run("BEGIN TRANSACTION")
					_.each(events, (e) => {
						self.db.run("INSERT INTO Events VALUES (?, ?, ?, ?, ?, ?)", uuid.v4(), e.streamId, e.version, new Date(), e.eventType, e.payload)
					})
					_.each(snapshots, (e) => {
						self.db.run("INSERT INTO Snapshots VALUES (?, ?, ?, ?, ?)", uuid.v4(), e.streamId, e.version, new Date(), e.payload)
					})
					self.db.run("COMMIT TRANSACTION")
					resolve()
				} catch (err) {
					self.db.run("ROLLBACK TRANSACTION")
					reject(err)
				}
			})
		})
    }
    
    //return a promise
    readSnapshot(id) {
		return new Promise((resolve, reject) => {
			this.db.get("SELECT * FROM Snapshots WHERE streamId = ? ORDER BY version DESC LIMIT 1", [id], (err, row) => {
				if (err) return reject(err)
				resolve(row)
			});
		})
    }
    
    //return a promise
    readEvents(id, fromVersion) {
		return new Promise((resolve, reject) => {
			this.db.all("SELECT * FROM Events WHERE streamId = ? AND version > ? ORDER BY version", [id, fromVersion], (err, rows) => {
				if (err) return reject(err)
				resolve(rows)
			});
		})
    }
}

module.exports = new SqlitePersistor()

Implementing hooks

CQRS-EventStore comes with a build-in hook functionality. We can execute a task after each commands.

A simple hook that print into the console on each mobile number update:

"use strict"

const util = require("util")

module.exports = evt => {
	console.log(util.format("Mobile number updated %s", evt.mobile))
}

Hooks need to be registered into the configurator

Configuration

Before to use CQRS-EventStore, we need to configure it.

The parameters are:

  • cacheExpiration: cache expiration in seconds, the default is 0 (unlimited).
  • cacheDeleteCheckInterval: The period in seconds, used for the automatic delete check interval. Default is 60 seconds.
  • repository: your extended persistance layer, if not provived an in-memory persistence will be used.
  • snapshotEvery: event threshold for the snapshot, the default is 0 (snapshot disabled). For example, if we assign 50, every 50 events we create the snapshot.
  • payloadSerializationFormat: payload serialization/compression, default is NodeEventStore.serializationFormats.stringify
    The "cqrs-eventstore" module exposes an 'enumeration' called serializationFormats. Available values are: stringify, zip, unserialized.

Usage Example


"use strict"

const NodeEventStore = require("cqrs-eventstore")
const UserInfoAggregate = require("./userInfoAggregate")
const mobileUpdatedHook = require("./mobile-updated-hook")

//We need to register the hooks here, the name of the hook must match the apply method
NodeEventStore.registerHook("MobileUpdated", mobileUpdatedHook)

//Configuration
const EventStore = NodeEventStore.initialize({
	cacheExpiration: 180,
	cacheDeleteCheckInterval: 60,
	repository: require("./sqlite-persistor"),
	snapshotEvery: 5,
	payloadSerializationFormat: NodeEventStore.serializationFormats.zip
})

const repository =  new EventStore.Repository(UserInfoAggregate)
let userInfoAggregate = new UserInfoAggregate(1)
userInfoAggregate.initialize("Gennaro", "Del Sorbo", "Main Street", "09762847")

repository.save(userInfoAggregate).then(() => {
	userInfoAggregate.updateMobile("333");
	userInfoAggregate.updateMobile("334");
	userInfoAggregate.updateMobile("335");
	userInfoAggregate.updateAddress("12, Main St.")
	userInfoAggregate.updateAddress("15, Main St.")
	repository.save(userInfoAggregate).then(() => {
		console.log("all saved")
		
		console.log("try a read")
		
		repository.read(1).then(userInfo => {
			console.log(userInfo.Mobile)
			console.log(userInfo.Address)
		}).catch(e => {
			console.log(e)
		});
	})
}).catch(err => {
	console.log(err)
})

Contributing

  1. clone this repo

  2. npm run setup

Run the demo

npm start

Run the tests

npm test

Run the tests and listen for a debugger

npm run test-debug