|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +function Transaction() {} |
| 4 | + |
| 5 | +Transaction.start = (data) => { |
| 6 | + console.log('\nstart transaction'); |
| 7 | + let delta = {}; |
| 8 | + |
| 9 | + const methods = { |
| 10 | + commit: () => { |
| 11 | + console.log('\ncommit transaction'); |
| 12 | + Object.assign(data, delta); |
| 13 | + delta = {}; |
| 14 | + }, |
| 15 | + rollback: () => { |
| 16 | + console.log('\nrollback transaction'); |
| 17 | + delta = {}; |
| 18 | + }, |
| 19 | + clone: () => { |
| 20 | + console.log('\nclone transaction'); |
| 21 | + const cloned = Transaction.start(data); |
| 22 | + Object.assign(cloned.delta, delta); |
| 23 | + return cloned; |
| 24 | + } |
| 25 | + }; |
| 26 | + |
| 27 | + return new Proxy(data, { |
| 28 | + get(target, key) { |
| 29 | + if (key === 'delta') return delta; |
| 30 | + if (methods.hasOwnProperty(key)) return methods[key]; |
| 31 | + if (delta.hasOwnProperty(key)) return delta[key]; |
| 32 | + return target[key]; |
| 33 | + }, |
| 34 | + getOwnPropertyDescriptor: (target, key) => ( |
| 35 | + Object.getOwnPropertyDescriptor( |
| 36 | + delta.hasOwnProperty(key) ? delta : target, key |
| 37 | + ) |
| 38 | + ), |
| 39 | + ownKeys() { |
| 40 | + const changes = Object.keys(delta); |
| 41 | + const keys = Object.keys(data).concat(changes); |
| 42 | + return keys.filter((x, i, a) => a.indexOf(x) === i); |
| 43 | + }, |
| 44 | + set(target, key, val) { |
| 45 | + console.log('set', key, val); |
| 46 | + if (target[key] === val) delete delta[key]; |
| 47 | + else delta[key] = val; |
| 48 | + return true; |
| 49 | + } |
| 50 | + }); |
| 51 | +}; |
| 52 | + |
| 53 | +// Usage |
| 54 | + |
| 55 | +const data = { name: 'Marcus Aurelius', born: 121 }; |
| 56 | + |
| 57 | +const transaction = Transaction.start(data); |
| 58 | +console.dir({ data }); |
| 59 | + |
| 60 | +transaction.name = 'Mao Zedong'; |
| 61 | +transaction.born = 1893; |
| 62 | +transaction.city = 'Shaoshan'; |
| 63 | +console.dir({ transaction }); |
| 64 | +console.dir({ delta: transaction.delta }); |
| 65 | + |
| 66 | +transaction.commit(); |
| 67 | +console.dir({ data }); |
| 68 | +console.dir({ transaction }); |
| 69 | +console.dir({ delta: transaction.delta }); |
| 70 | + |
| 71 | +transaction.born = 1976; |
| 72 | +console.dir({ transaction }); |
| 73 | +console.dir({ delta: transaction.delta }); |
| 74 | + |
| 75 | +transaction.rollback(); |
| 76 | +console.dir({ data }); |
| 77 | +console.dir({ transaction }); |
| 78 | +console.dir({ delta: transaction.delta }); |
0 commit comments