Quickstart

Install

1
npm i --save serverless-cqrs
2
npm i --save serverless-cqrs.memory-adapter
Copied!

Usage

To start, you need Actions and a Reducer. So let's write simple ones:
actions.js
1
const actions = {
2
addTodo: (state, payload) => {
3
if (!payload.title) throw new Error('titleMissing')
4
5
return [{
6
type: 'TodoAdded',
7
title: payload.title,
8
at: Date.now(),
9
}]
10
}
11
}
12
13
module.exports = actions
Copied!
reducer.js
1
const initialState = {
2
todos: []
3
}
4
5
const reducer = (state, event) => {
6
switch (event.type) {
7
case 'TodoAdded':
8
return {
9
todos: [
10
...state.todos,
11
{ title: event.title },
12
]
13
}
14
15
default:
16
return state
17
}
18
}
19
20
module.exports = (events, state=initialState) => events.reduce(reducer, state)
Copied!
Above we have a basic action and reducer.
    The action ,addTodo, does some basic validation to check the presence of a title and if it succeeds, returns a new event with the type TodoAdded.
    When that event is run through the reducer, a new todo is appended to the list.
Next, we build an adapter to help us persist the events.
adapter.js
1
const memoryAdapterBuilder = require('serverless-cqrs.memory-adapter')
2
module.exports = memoryAdapterBuilder.build({
3
entityName: 'todo'
4
})
Copied!
This adapter will let us persist events and read-model projections in memory.
Finally, we use these to build our read and write model.
app.js
1
const {
2
writeModelBuilder,
3
readModelBuilder,
4
} = require('serverless-cqrs')
5
6
const actions = require('./actions')
7
const reducer = require('./reducer')
8
const adapter = require('./adapter')
9
10
module.exports.writeModel = writeModelBuilder.build({
11
actions,
12
reducer,
13
adapter,
14
})
15
16
module.exports.readModel = readModelBuilder.build({
17
reducer,
18
adapter,
19
eventAdapter: adapter,
20
})
Copied!
That's it!

Try it live

Last modified 2yr ago
Copy link