0.15.0 • Published 4 months ago

@getanthill/event-source v0.15.0

Weekly downloads
74
License
MIT
Repository
gitlab
Last release
4 months ago

getanthill Event-Source

pipeline Quality Gate Status

Coverage Reliability Rating

Getting Started

Install the package

npm install -S @getanthill/event-source

Define your class

The following will be extended with the Event-Source functionalities.

// src/models/Users.ts
import { EventSourcedFactory } from '@getanthill/event-source';

/**
 * This is the main reducer for your events.
 * > f(state_{i}, event) = state_{i+1}
 */
const reducer = (state, event) => {
  if (event.type === 'CREATED') {
    return {
      firstname: event.firstname,
    };
  }

  return state;
};

export default class Users extends EventSourced('users', reducer) {
  /**
   * Create a new user
   * @param {string} firstname The user firstname
   * @return {Promise<object>} Updated state
   */
  create(firstname) {
    return this.handle(() => [
      {
        type: 'CREATED',
        firstname,
      },
    ]);
  }
}

Use your Event-Sourced class

// src/business/users.ts
import Users from '../models/Users';

/**
 * Create a user
 *
 * @param {object} db MongoDb connection
 * @param {string} firstname User firstname
 * @return {Promise<object>} State after success
 */
function createUser(db, firstname) {
  const user = new Users(db, 1); // 1 = correlation_id

  return user.create('John');
}

In your database, we will now have access to the events in the collection users_events:

db.users_events.find().pretty();
{
  "type": "CREATED",
  "correlation_id": 1,
  "version": 0,
  "firstname": "John",
  "created_at": "2020-11-01T06:05:43.210Z"
}

and also the final resulting state of your object:

db.users.find().pretty();
{
  "correlation_id": 1,
  "version": 0,
  "firstname": "John"
}

Conclusion

Now that you are able to have a fully Event-Source featured class, you can read further on what is possible to create with this library and how to custom a bit some features such as the correlation_id naming.

0.15.0

4 months ago

0.14.0

1 year ago

0.14.1

1 year ago

0.13.0

1 year ago

0.13.1

1 year ago

0.12.4

1 year ago

0.12.5

1 year ago

0.12.6

1 year ago

0.11.0

1 year ago

0.10.1

1 year ago

0.12.0

1 year ago

0.10.2

1 year ago

0.12.1

1 year ago

0.12.2

1 year ago

0.12.3

1 year ago

0.10.0

2 years ago

0.9.4

2 years ago

0.9.3

2 years ago

0.9.0

2 years ago

0.8.0

2 years ago

0.9.2

2 years ago

0.9.1

2 years ago

0.7.1

2 years ago

0.7.0

2 years ago

0.6.2

2 years ago

0.6.1

2 years ago

0.5.2

2 years ago

0.6.0

2 years ago

0.5.0

2 years ago

0.5.1

2 years ago

0.4.1

3 years ago

0.4.0

3 years ago

0.3.0

3 years ago

0.2.3

3 years ago

0.2.2

3 years ago

0.2.1

3 years ago

0.2.0

3 years ago

0.1.1

3 years ago

0.1.0

3 years ago