Files: 2fc95bb03dc629547fc2632a480d945bf1b89cef / stores / ledger.js
2019 bytesRaw
1 | const Flume = require('flumedb') |
2 | const Reduce = require('flumeview-reduce') |
3 | const FlumeLog = require('flumelog-offset') |
4 | const {pull, once, drain} = require('pull-stream') |
5 | const codec = require('flumecodec') |
6 | |
7 | function ledger (state, emitter) { |
8 | state.accounts = {} |
9 | state.entries = [] |
10 | |
11 | const db = Flume(FlumeLog('.test.db', {codec: codec.json})) |
12 | .use('entries', Reduce( 1, entriesReducer, null, null, [])) |
13 | .use('accounts', Reduce(1, accountReducer, null, null, {})) |
14 | |
15 | pull(db.accounts.stream({live: true}), drain(acct => console.log('account stream:', acct))) |
16 | pull(db.entries.stream({live: true}), drain(entry => console.log('entries stream:', entry))) |
17 | |
18 | const onDone = () => console.log('DONE') |
19 | pull(db.accounts.stream(), drain(acctState => { |
20 | console.log('ACCOUNT STATE', acctState) |
21 | state.accounts = acctState |
22 | emitter.emit.RENDER |
23 | }, onDone)) |
24 | pull(db.entries.stream(), drain(entryState => { |
25 | console.log('ENTRY STATE', entryState) |
26 | state.entries = entryState |
27 | emitter.emit.RENDER |
28 | }, onDone)) |
29 | |
30 | function onLoad () { |
31 | emitter.on('accounts', onEvent) |
32 | emitter.on('entries', onEvent) |
33 | } |
34 | |
35 | function onEvent (data) { |
36 | db.append(data, (err, seq) => { |
37 | if (err) throw err |
38 | emitter.emit(state.events.RENDER) |
39 | }) |
40 | } |
41 | |
42 | emitter.on('DOMContentLoaded', onLoad) |
43 | |
44 | function entriesReducer (acc, item) { |
45 | if (item.type !== 'entries') return acc |
46 | acc.push(item) |
47 | |
48 | return acc |
49 | } |
50 | |
51 | function accountReducer (acc, item) { // TODO account for account creation of existing account |
52 | if (item.type === 'entries') { |
53 | const {msg} = item |
54 | const debit = acc[msg.debit].debit += msg.amount |
55 | const credit = acc[msg.credit].credit += msg.amount |
56 | |
57 | return acc |
58 | } |
59 | if (item.type !== 'accounts') return acc |
60 | const { msg } = item |
61 | |
62 | if (!acc[msg.name]) { |
63 | acc[msg.name] = msg |
64 | |
65 | return acc |
66 | } |
67 | |
68 | Object.assign(acc[msg.name], msg) |
69 | Object.assign(state.accounts[msg.name], msg) |
70 | return acc |
71 | } |
72 | } |
73 | |
74 | |
75 | module.exports = ledger |
76 |
Built with git-ssb-web