UNPKG

1.29 kBJavaScriptView Raw
1var _ = require('lodash')
2var Store = require('./store')
3
4// Compose every function with fn
5function composeAll(obj, fn) {
6 for (var key in obj) {
7 if (_.isFunction(obj[key])) {
8 obj[key] = _.compose(fn, obj[key])
9 }
10 }
11}
12
13function Low(filename) {
14 // Create a new JSON file and get object
15 if (filename) {
16 var store = new Store(filename)
17 var object = store.object
18 } else {
19 var object = {}
20 }
21
22 function chain(name) {
23 // Create empty array if it doesn't exist
24 object[name] = object[name] || []
25
26 if (filename) store.save()
27
28 // Chain array
29 var chainedArray = _.chain(object[name])
30
31 // Hack, wrap every Lo-Dash function to call save.
32 // Save is however throttled and only happens if database object
33 // has changed.
34 // With Node 0.12 and Object.observe support, this bit of code should
35 // removed :)
36 if (filename) composeAll(chainedArray, function(arg) {
37 store.save()
38 return arg
39 })
40
41 return chainedArray
42 }
43
44 // Expose store object
45 chain.object = object
46
47 // Call it to manually save database
48 chain.save = function() {
49 if (store) store.save()
50 }
51
52 return chain
53}
54
55function low(filename) {
56 return new Low(filename)
57}
58
59low.mixin = function(source) {
60 _.mixin(source)
61}
62
63module.exports = low
\No newline at end of file