Guest User

Untitled

a guest
Feb 23rd, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. class ODM {
  2.  
  3. constructor(document) {
  4. // get class name
  5. const name = this.constructor.name;
  6.  
  7. // add unique id
  8. if (!document._id) document._id = Math.random().toString();
  9.  
  10. // create document
  11. if (!db[name]) db[name] = {};
  12. db[name][document._id] = document;
  13.  
  14. // define accessors
  15. const configuration = {};
  16. Object.keys(document).forEach((prop) => {
  17. configuration[prop] = {
  18. get() {
  19. const value = db[name][document._id][prop];
  20. // return an instance or a value
  21. return value.indexOf('@') !== -1 ? instances[value.replace('@', '')] : value;
  22. },
  23. set(value) {
  24. if (classes[value.constructor.name]) {
  25. // store the id of the instance
  26. db[name][document._id][prop] = value._id;
  27. } else {
  28. db[name][document._id][prop] = value;
  29. }
  30. }
  31. };
  32. });
  33.  
  34. // set accessors
  35. Object.defineProperties(this, configuration);
  36.  
  37. // add it to the list of instances
  38. instances[document._id] = this;
  39. }
  40. }
Add Comment
Please, Sign In to add comment