-
Notifications
You must be signed in to change notification settings - Fork 89
/
index.js
84 lines (69 loc) · 2.26 KB
/
index.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import express from 'express';
import bodyParser from 'body-parser';
import uuid from 'uuid';
import createStore from 'resolve-es';
import esDriver from 'resolve-es-file';
import createBus from 'resolve-bus';
import busDriver from 'resolve-bus-memory';
import commandHandler from 'resolve-command';
import query from 'resolve-query';
import todoCardAggregate from './aggregates/TodoCard';
import todoItemAggregate from './aggregates/TodoItem';
import cardsProjection from './projections/cards';
import cardDetailsProjection from './projections/cardDetails';
const setupMiddlewares = (app) => {
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('views', './views');
app.set('view engine', 'pug');
};
const app = express();
app.use(express.static('static'));
const eventStore = createStore({
driver: esDriver({ pathToFile: './event_store.json' })
});
const bus = createBus({ driver: busDriver() });
const execute = commandHandler({
store: eventStore,
bus,
aggregates: [todoCardAggregate, todoItemAggregate]
});
const queries = query({
store: eventStore,
bus,
projections: [cardsProjection, cardDetailsProjection]
});
setupMiddlewares(app);
app.get('/', (req, res) =>
queries('cards').then(inventoryItems =>
res.render('index', {
items: Object.values(inventoryItems)
})
)
);
app.get('/:card', (req, res) =>
queries('cardDetails').then(items =>
res.render('cardDetails', { card: items.cards[req.params.card] })
)
);
app.post('/command', (req, res) => {
const command = Object.keys(req.body)
.filter(key => key !== 'aggregateName' || key !== 'returnUrl')
.reduce((result, key) => {
result[key] = req.body[key];
return result;
}, {});
const redirectUrl = req.body.returnUrl || '/';
command.aggregateId = command.aggregateId || uuid.v4();
command.aggregateName = req.body.aggregateName;
execute(command)
.catch((err) => {
// eslint-disable-next-line no-console
console.log(err);
})
.then(() => res.redirect(redirectUrl));
});
app.listen(3000, () => {
// eslint-disable-next-line no-console
console.log('Example app listening on port 3000!');
});