mm.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. const ObjectID = require("mongodb").ObjectID;
  2. const asynchronize = require('./asynchronize').asynchronize
  3. let i=0;
  4. module.exports = db => {
  5. class Savable {
  6. constructor(obj, ref, empty=false){
  7. this._id = null
  8. this._ref = ref
  9. this._class = this.__proto__.constructor.name
  10. this._empty = true
  11. Savable.addClass(this.__proto__.constructor)
  12. if (obj){
  13. this.populate(obj)
  14. this._empty = empty
  15. }
  16. }
  17. saveRelations(){
  18. this._loadRelations = {};
  19. for (const relation in this.__proto__.constructor.relations){
  20. this._loadRelations[relation] = this[relation] instanceof Array ? [...this[relation]] : this[relation]
  21. }
  22. }
  23. populate(obj){
  24. const convertSavables = (obj) => {
  25. for (const key in obj){
  26. if (Savable.isSavable(obj[key])){
  27. obj[key] = (this._ref &&
  28. obj[key]._id.toString() == this._ref._id.toString()) ?
  29. this._ref :
  30. Savable.newSavable(obj[key], this)
  31. }
  32. else if (typeof obj[key] === 'object'){
  33. convertSavables(obj[key])
  34. }
  35. }
  36. }
  37. Object.assign(this, obj)
  38. convertSavables(this)
  39. this.saveRelations()
  40. //this._id = obj._id
  41. }
  42. get _empty(){
  43. return !!this.then
  44. }
  45. set _empty(value){
  46. if (value){
  47. this.then = (cb, err) => {
  48. let stamp = (new Date()).getTime()
  49. delete this.then
  50. if (!this._id) err(new ReferenceError('Id is empty'))
  51. if (!this._class) err(new ReferenceError('Class is empty'))
  52. this.collection.findOne(this._id).then( data => {
  53. if (!data){
  54. err(new ReferenceError('Document Not Found'))
  55. }
  56. this.populate(data)
  57. cb(this)
  58. })
  59. return this
  60. }
  61. }
  62. else {
  63. delete this.then
  64. }
  65. }
  66. get createdAt(){
  67. return this._id ? new Date(this._id.getTimestamp()) : null
  68. }
  69. get collection(){
  70. return db.collection(this._class)
  71. }
  72. async save(noRefs=false, noSync=false){
  73. if (this.empty) return;
  74. const syncRelations = async () => {
  75. if (noSync) return
  76. if (!(this && this.__proto__ && this.__proto__.constructor && this.__proto__.constructor.relations)) return
  77. async function getValueByField(field, savable) {
  78. let path = field.split('.');
  79. await savable//.catch(e => console.log('GET VALUE BY FIELD ERROR'));
  80. let result = savable;
  81. let prev;
  82. let lastKey = path.pop()
  83. while (prev = result, result = result[path.shift()] && path.length);
  84. return {value: prev[lastKey], obj: prev, lastKey};
  85. }
  86. let setBackRef = async (backRef, foreignSavable) => {
  87. const {value: backRefValue,
  88. obj: backRefObj,
  89. lastKey: backRefKey} = await getValueByField(backRef, foreignSavable)
  90. if (backRefValue instanceof Array){
  91. if (!backRefValue.includes(this)){
  92. backRefValue.push(this)
  93. }
  94. }
  95. else {
  96. backRefObj[backRefKey] = this
  97. }
  98. noRefs || await foreignSavable.save(true)
  99. }
  100. for (const relation in this.__proto__.constructor.relations){
  101. const backRef = this.__proto__.constructor.relations[relation]
  102. const loadRelation = this._loadRelations[relation]
  103. const loadRelationAsArray = loadRelation instanceof Savable ? [loadRelation] : loadRelation
  104. let {value, obj, lastKey: key} = await getValueByField(relation, this)
  105. const valueAsArray = value instanceof Savable ? [value] : value
  106. if (loadRelationAsArray){
  107. const removedRefs = valueAsArray ? loadRelationAsArray.filter(ref => !valueAsArray.includes(ref)) : loadRelationAsArray
  108. for (const ref of removedRefs){
  109. try {
  110. await ref
  111. }
  112. catch (e) {console.log('SYNC RELATIONS ERROR') }
  113. if (ref[backRef] instanceof Array){
  114. ref[backRef] = ref[backRef].filter(br => br._id !== this._id)
  115. }
  116. else {
  117. ref[backRef] = null
  118. }
  119. noRefs || await ref.save(true)
  120. }
  121. }
  122. if (valueAsArray){
  123. for (const foreignSavable of valueAsArray){
  124. await setBackRef(backRef, foreignSavable)
  125. }
  126. }
  127. }
  128. }
  129. async function recursiveSlicer(obj){
  130. let result = obj instanceof Array ? [] : {}
  131. for (const key in obj){
  132. if (obj[key] && typeof obj[key] === 'object'){
  133. if (obj[key] instanceof Savable){
  134. if (!(obj[key]._id)){
  135. await obj[key].save().catch(err => console.log('ERR', err))
  136. }
  137. result[key] = {_id: obj[key]._id, _class: obj[key]._class}
  138. }
  139. else {
  140. result[key] = await recursiveSlicer(obj[key])
  141. }
  142. }
  143. else {
  144. result[key] = obj[key]
  145. }
  146. }
  147. return result;
  148. }
  149. const {_id, _empty, _ref, _loadRelations, then, ...toSave} = await recursiveSlicer(this)
  150. //TODO: UPSERT
  151. if (!this._id){ //first time
  152. const { insertedId } = await this.collection.insertOne(toSave)
  153. this._id = insertedId
  154. }
  155. else { //update
  156. await this.collection.updateOne({_id: this._id}, {$set: toSave}).catch(err => console.log('UPDATE ERR', err))
  157. }
  158. await syncRelations()
  159. this.saveRelations()
  160. }
  161. async delete(noRefs=false){
  162. if (!noRefs) for (const relation in this.__proto__.constructor.relations){
  163. const backRef = this.__proto__.constructor.relations[relation]
  164. const loadRelation = this._loadRelations && this._loadRelations[relation]
  165. const loadRelationAsArray = loadRelation instanceof Savable ? [loadRelation] : loadRelation
  166. if (loadRelationAsArray){
  167. for (const ref of loadRelationAsArray){
  168. try {
  169. await ref
  170. }
  171. catch (e) {console.log('DELETE SYNC RELATIONS ERROR') }
  172. if (ref[backRef] instanceof Array){
  173. ref[backRef] = ref[backRef].filter(br => br._id !== this._id)
  174. }
  175. else {
  176. ref[backRef] = null
  177. }
  178. await ref.save(true, true)
  179. }
  180. }
  181. }
  182. const id = this._id
  183. const col = this._class && this.collection
  184. for (let key in this)
  185. delete this[key]
  186. delete this.__proto__
  187. if (col)
  188. return await col.deleteOne({_id: id})
  189. }
  190. static isSavable(obj){
  191. return obj && obj._id && obj._class
  192. }
  193. static newSavable(obj, ref, empty=true){
  194. let className = obj._class || "Savable"
  195. if (obj.__proto__.constructor === Savable.classes[className]){
  196. return obj
  197. }
  198. return new Savable.classes[className](obj, ref, empty)
  199. }
  200. static addClass(_class){ //explicit method to add class to Savable registry for instantiate right class later
  201. Savable.classes[_class.name] = _class
  202. }
  203. static get m(){
  204. return new Proxy({}, {
  205. get(obj, _class){
  206. if (_class in obj){
  207. return obj[_class]
  208. }
  209. return obj[_class] = {
  210. * find(query, projection, cursorCalls){
  211. let cursor = db.collection(_class).find(query, projection)
  212. for (let [method, params] of Object.entries(cursorCalls)){
  213. if (typeof cursor[method] !== "function"){
  214. throw new SyntaxError(`Wrong cursor method ${method}`)
  215. }
  216. cursor = cursor[method](...params)
  217. }
  218. let cursorGen = asynchronize({s: cursor.stream(),
  219. chunkEventName: 'data',
  220. endEventName: 'close'})
  221. for (const pObj of cursorGen()){
  222. yield new Promise((ok, fail) =>
  223. pObj.then(obj => ok(Savable.newSavable(obj, null, false)),
  224. err => fail(err)))
  225. }
  226. },
  227. async findOne(query, projection){
  228. let result = await db.collection(_class).findOne(query, projection)
  229. if (result)
  230. return Savable.newSavable(result, null, false)
  231. return result
  232. }
  233. }
  234. },
  235. set(obj, propName, value){
  236. }
  237. })
  238. }
  239. static get relations(){
  240. //empty default relations, acceptable: {field: foreignField}, where:
  241. //field and foreign field can be Savable, Array or Set
  242. //both fields can be specified as "field", "field.subfield"
  243. //or field: {subfield: foreignField} //TODO later if needed
  244. //TODO: move it into object instead of class to give more flexibility, for example
  245. //if person has children, it can have backRef father or mother depending on sex:
  246. //return {
  247. // children: this.sex === 'male' ? 'father': 'mother'
  248. //}
  249. return {}
  250. }
  251. }
  252. Savable.classes = {Savable}
  253. /**
  254. * sliceSavable - slice (limit) Savables for some permission
  255. * Array userACL - array of objectIDs, words or savable refs - current user, group objectid, or `tags` or `role` (ACL)
  256. */
  257. function sliceSavable(userACL){
  258. userACL = userACL.map(tag => tag.toString())
  259. console.log(userACL)
  260. class SlicedSavable extends Savable {
  261. constructor(...params){
  262. super (...params)
  263. if (!this._empty){
  264. this.___permissionsPrepare()
  265. }
  266. }
  267. ___permissionsPrepare(){
  268. if (this._empty) return
  269. if (!this.___permissions) this.___permissions = {}
  270. for (let [perm, acl] of Object.entries(this.__proto__.constructor.defaultPermissions)){
  271. if (!this.___permissions[perm]){
  272. this.___permissions[perm] = [...acl]
  273. }
  274. }
  275. }
  276. ___permissionCan(permission, permissions=this.___permissions){
  277. const acl = (permissions &&
  278. permissions[permission] ||
  279. this.__proto__.constructor.defaultPermissions[permission]).map(tag => tag.toString())
  280. if (acl.includes('owner') && this.___owner && userACL.includes(this.___owner.toString())){
  281. return true
  282. }
  283. for (let uTag of userACL){
  284. if (acl.includes(uTag)){
  285. return true
  286. }
  287. }
  288. return false
  289. }
  290. populate(obj){ //place to check read permission
  291. if (!this.___permissionCan('read', obj.___permissions)){
  292. throw new ReferenceError(`No Access To Entity ${this._id} of class ${this._class}`)
  293. }
  294. super.populate(obj)
  295. }
  296. async save(...params){
  297. if (!this._id && !this.___permissionCan('create'))
  298. throw new ReferenceError(`Permissison denied Create Entity of class ${this._class}`)
  299. if (!this.___permissionCan('write'))
  300. throw new ReferenceError(`Permissison denied Save Entity ${this._id} of class ${this._class}`)
  301. if (!this._id){
  302. this.___owner = userACL[0] //TODO fix objectid troubles
  303. console.log(typeof this.___owner, this.___owner)
  304. }
  305. return await super.save(...params)
  306. }
  307. async delete(noRefs=false){
  308. if (!this.___permissionCan('delete'))
  309. throw new ReferenceError(`Permissison denied Delete Entity ${this._id} of class ${this._class}`)
  310. return await super.delete(noRefs)
  311. }
  312. static get defaultPermissions(){
  313. return {
  314. //savable refs, objectid's, words like 'tags' or 'roles'
  315. read: ['owner', 'user'],
  316. write: ['owner', 'admin'],
  317. create: ['user'],
  318. delete: ['admin'],
  319. /*permission
  320. * TODO: permissions for read and write permissions
  321. *
  322. */
  323. }
  324. }
  325. }
  326. return SlicedSavable
  327. }
  328. return {Savable, sliceSavable}
  329. }