git ssb

0+

dangerousbeans / web-bootloader



forked from Dominic / web-bootloader

Tree: ef1a2eaa163709173d29cc9f3fc446695e466fe7

Files: ef1a2eaa163709173d29cc9f3fc446695e466fe7 / log.js

1449 bytesRaw
1var u = require('./util')
2
3/*
4 this uses localStorage, so it doesn't need async,
5 but i used async api anyway,
6 so it will be easy to switch to indexeddb.
7*/
8
9module.exports = function (prefix, storage) {
10 //pass in non-local storage, to make testing easy.
11 storage = storage || localStorage
12 var log
13 function _append (data, cb) {
14 var log = u.parse(storage[prefix]) || []
15 log.unshift(data)
16 storage[prefix] = JSON.stringify(log)
17 cb(null, data)
18 }
19
20 function filtered (log) {
21 var revert = null
22 var output = []
23 for(var i = 0; i < log.length; i++) {
24 var item = log[i]
25 if(revert && revert <= item.ts) //this op was reverted.
26 ;
27 else if(item.revert)
28 revert = item.revert
29 else
30 output.push(item)
31 }
32 return output
33 }
34
35 function getLog() {
36 return u.parse(storage[prefix]) || []
37 }
38
39 return log = {
40 head: function (cb) {
41 cb(null, filtered(getLog())[0])
42 },
43 filtered: function (cb) {
44 cb(null, filtered(getLog()))
45 },
46 unfiltered: function (cb) {
47 cb(null, getLog())
48 },
49 append: function (data, cb) {
50 _append({value: data, ts: Date.now()}, cb)
51 },
52 revert: function (ts, cb) {
53 if(!ts) return cb(new Error('log.revert: must provide ts to revert to'))
54 _append({revert: ts, ts: Date.now()}, function (err) {
55 if(err) cb(err)
56 else cb(null, filtered(getLog())[0])
57 })
58 }
59 }
60}
61
62
63

Built with git-ssb-web