git ssb

0+

punkmonk / double



Tree: 98627fd6bc0b024c3ddfe4bbe1f0a5bf18e9cbde

Files: 98627fd6bc0b024c3ddfe4bbe1f0a5bf18e9cbde / stores / ledger.js

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

Built with git-ssb-web