Created
October 30, 2019 15:11
-
-
Save Liroo/bb60eba7fc25d438d54b26941c214b57 to your computer and use it in GitHub Desktop.
Use of javascript Proxy for a new object relational concept in Javascript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let _instanceRelateDb = null; | |
class RelateDb { | |
constructor() { | |
if (_instanceRelateDb) { return _instanceRelateDb; } | |
_instanceRelateDb = this; | |
this._db = {}; | |
} | |
set(relateId, relateObj) { | |
this._db[relateId] = relateObj; | |
} | |
get(relateId) { | |
return this._db[relateId]; | |
} | |
} | |
class RelateId { | |
constructor(id) { | |
this._id = id; | |
} | |
getId() { | |
return this._id; | |
} | |
} | |
function isRelateId(obj) { | |
return obj && obj instanceof RelateId; | |
} | |
const handler = { | |
get: function(obj, key) { | |
let value = obj[key]; | |
if (isRelateId(value)) { | |
return new RelateDb().get(value.getId()); | |
} | |
return value; | |
}, | |
}; | |
function relate(obj) { | |
if (!obj.id) { | |
obj.id = Symbol('__RELATE_ID__'); | |
} | |
let relateObj = new Proxy(obj, handler); | |
new RelateDb().set(obj.id, relateObj); | |
return relateObj; | |
} | |
let first = relate({ | |
key: '1', | |
nest: { | |
key: '2', | |
}, | |
}); | |
let second = relate({ | |
firstLn: new RelateId(first.id), | |
}); | |
console.log(second.firstLn.key); // 1 | |
console.log(second.firstLn.nest.key); // 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment