Implement LazyArray.splice(), implement unshift/shift/push/pop in terms of splice...
[logjson.git] / LazyObject.mjs
1 import assert from 'assert'
2 import LazyValue from './LazyValue.mjs'
3
4 class LazyObject extends LazyValue {
5   constructor(transaction, ptr_len, object) {
6     super(transaction, ptr_len)
7     this.object = object || {}
8   }
9
10   has(key) {
11     assert(typeof key === 'string')
12     return Object.prototype.hasOwnProperty.call(this.object, key)
13   }
14
15   async get(key, default_value) {
16     assert(typeof key === 'string')
17     if (!Object.prototype.hasOwnProperty.call(this.object, key)) {
18       if (default_value === undefined)
19         return undefined
20       this.set(key, this.transaction.json_to_logjson(default_value))
21     }
22
23     let value = this.object[key]
24     if (value instanceof Array) {
25       value = await this.transaction.read(value)
26       this.object[key] = value
27     }
28     return value
29   }
30
31   set(key, value) {
32     assert(typeof key === 'string')
33     assert(
34       typeof value !== 'object' ||
35       value === null ||
36       (value instanceof LazyValue && value.transaction === this.transaction)
37     )
38     this.ptr_len = null // mark dirty
39     this.object[key] = value
40   }
41
42   delete(key) {
43     if (this.has(key)) {
44       this.ptr_len = null // mark dirty
45       delete this.object[key]
46     }
47   }
48
49   keys() {
50     let keys = []
51     for (let i in this.object)
52       keys.push(i)
53     return keys
54   }
55
56   async commit() {
57     for (let i in this.object) {
58       let value = this.object[i]
59       if (value instanceof LazyValue) {
60         if (await value.commit())
61           this.ptr_len = null // mark dirty
62         this.object[i] = value.ptr_len
63       }
64     }
65
66     if (this.ptr_len === null) {
67       this.ptr_len = await this.transaction.database.write(this.object)
68       return true
69     }
70     return false
71   }
72 }
73
74 export default LazyObject