|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +function Transaction() {} |
| 4 | + |
| 5 | +Transaction.start = (data) => { |
| 6 | + console.log('\nstart transaction'); |
| 7 | + const events = { |
| 8 | + commit: [], rollback: [], timeout: [], change: [] |
| 9 | + }; |
| 10 | + let delta = {}; |
| 11 | + |
| 12 | + const emit = (name) => { |
| 13 | + const event = events[name]; |
| 14 | + for (const listener of event) listener(data); |
| 15 | + }; |
| 16 | + |
| 17 | + const methods = { |
| 18 | + commit: () => { |
| 19 | + Object.assign(data, delta); |
| 20 | + delta = {}; |
| 21 | + emit('commit'); |
| 22 | + }, |
| 23 | + rollback: () => { |
| 24 | + delta = {}; |
| 25 | + emit('rollback'); |
| 26 | + }, |
| 27 | + clone: () => { |
| 28 | + const cloned = Transaction.start(data); |
| 29 | + Object.assign(cloned.delta, delta); |
| 30 | + return cloned; |
| 31 | + }, |
| 32 | + on: (name, callback) => { |
| 33 | + const event = events[name]; |
| 34 | + if (event) event.push(callback); |
| 35 | + } |
| 36 | + }; |
| 37 | + |
| 38 | + return new Proxy(data, { |
| 39 | + get(target, key) { |
| 40 | + if (key === 'delta') return delta; |
| 41 | + if (methods.hasOwnProperty(key)) return methods[key]; |
| 42 | + if (delta.hasOwnProperty(key)) return delta[key]; |
| 43 | + return target[key]; |
| 44 | + }, |
| 45 | + getOwnPropertyDescriptor: (target, key) => ( |
| 46 | + Object.getOwnPropertyDescriptor( |
| 47 | + delta.hasOwnProperty(key) ? delta : target, key |
| 48 | + ) |
| 49 | + ), |
| 50 | + ownKeys() { |
| 51 | + const changes = Object.keys(delta); |
| 52 | + const keys = Object.keys(data).concat(changes); |
| 53 | + return keys.filter((x, i, a) => a.indexOf(x) === i); |
| 54 | + }, |
| 55 | + set(target, key, val) { |
| 56 | + console.log('set', key, val); |
| 57 | + if (target[key] === val) delete delta[key]; |
| 58 | + else delta[key] = val; |
| 59 | + return true; |
| 60 | + } |
| 61 | + }); |
| 62 | +}; |
| 63 | + |
| 64 | +function DatasetTransaction(dataset) { |
| 65 | + this.dataset = dataset; |
| 66 | +} |
| 67 | + |
| 68 | +DatasetTransaction.start = function(dataset) { |
| 69 | + // place implementation here |
| 70 | + return new DatasetTransaction(dataset); |
| 71 | +}; |
| 72 | + |
| 73 | +DatasetTransaction.prototype.commit = function() { |
| 74 | + // place implementation here |
| 75 | +}; |
| 76 | + |
| 77 | +DatasetTransaction.prototype.rollback = function() { |
| 78 | + // place implementation here |
| 79 | +}; |
| 80 | + |
| 81 | +// Usage |
| 82 | + |
| 83 | +const data = [ |
| 84 | + { name: 'Marcus Aurelius', born: 121 }, |
| 85 | + { name: 'Marcus Aurelius', born: 121 }, |
| 86 | + { name: 'Marcus Aurelius', born: 121 }, |
| 87 | +]; |
| 88 | + |
| 89 | +const transaction = DatasetTransaction.start(data); |
| 90 | + |
| 91 | +for (const person of transaction.dataset) { |
| 92 | + person.city = 'Shaoshan'; |
| 93 | +} |
| 94 | + |
| 95 | +transaction.commit(); |
| 96 | + |
| 97 | +console.dir({ data }); |
0 commit comments