The write-model
exports two functions repositoryBuilder
and commandServiceBuilder
.
To initialize the model, you pass an adapter
and reducer
to the repositoryBuilder
to generate a repository
. Then you pass the repository
and actions
to the commandServiceBuilder
to generate a list of commands
const {
repositoryBuilder,
commandServiceBuilder,
} = require('serverless-cqrs.write-mode')
const adapter = require('./adapter')
const reducer = require('./reducer')
const actions = require('./actions')
const repository = repositoryBuilder.build({
adapter,
reducer,
})
module.exports = commandServiceBuilder.build({
repository,
actions,
})
Takes a reducer and an adapter and returns a repository. A repository is the layer of our Onion Architecture (see Introduction) which handles data persistence.
The write-model
repository has a single method called getById
. When invoked, it uses the adapter to load all events for given ID and runs them through the reducer to calculate the current state. It returns an object that contains state
and also a save
method, which is used to append new events.
build({ adapter, reducer })
builds a repository
attribute | type | description |
---|---|---|
adapter |
object |
Any object which implements the write-model Adapter Interface. |
reducer |
function |
a function which, given a list of events, knows how to calculate the current state of an object. |
{ getById }
- an object with the getById
function.
getById(id)
Loads and returns the current state of an entity. Also returns a save
function for appending new events to the data store.
attribute | type | description |
---|---|---|
id |
string |
the id of the entity |
{ state, save }
- an object containing an arbitrary state
object, and a save
function.
save(events)
Appends new events to the datastore
attribute | type | description |
---|---|---|
events |
array |
an array of arbitrary event objects |
null
Takes a list of actions and a repository and returns an object where action names map to executable commands.
Each command accepts an id and a payload. When invoked, a command loads the current state of the entity from the repo and passes it, and the payload, to the action. The action will perform its validation and if successful, generate one or more events. The command forwards those events to the repository to be appended to the entity.
build({ actions, repository })
Turns actions into commands that can be executed on real objects.
attribute | type | description |
---|---|---|
actions |
object |
Domain actions |
repository |
object |
generated by the repositoryBuilder |
commands
- where keys are actions names and values are functions which accept an id
and payload