mm.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 this;
  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. return this
  161. }
  162. async delete(noRefs=false){
  163. if (!noRefs) for (const relation in this.__proto__.constructor.relations){
  164. const backRef = this.__proto__.constructor.relations[relation]
  165. const loadRelation = this._loadRelations && this._loadRelations[relation]
  166. const loadRelationAsArray = loadRelation instanceof Savable ? [loadRelation] : loadRelation
  167. if (loadRelationAsArray){
  168. for (const ref of loadRelationAsArray){
  169. try {
  170. await ref
  171. }
  172. catch (e) {console.log('DELETE SYNC RELATIONS ERROR') }
  173. if (ref[backRef] instanceof Array){
  174. ref[backRef] = ref[backRef].filter(br => br._id !== this._id)
  175. }
  176. else {
  177. ref[backRef] = null
  178. }
  179. await ref.save(true, true)
  180. }
  181. }
  182. }
  183. const id = this._id
  184. const col = this._class && this.collection
  185. for (let key in this)
  186. delete this[key]
  187. delete this.__proto__
  188. if (col)
  189. return await col.deleteOne({_id: id})
  190. }
  191. static isSavable(obj){
  192. return obj && obj._id && obj._class
  193. }
  194. static newSavable(obj, ref, empty=true){
  195. let className = obj._class || "Savable"
  196. if (obj.__proto__.constructor === Savable.classes[className]){
  197. return obj
  198. }
  199. return new Savable.classes[className](obj, ref, empty)
  200. }
  201. static addClass(_class){ //explicit method to add class to Savable registry for instantiate right class later
  202. Savable.classes[_class.name] = _class
  203. }
  204. static get m(){
  205. return new Proxy({}, {
  206. get(obj, _class){
  207. if (_class in obj){
  208. return obj[_class]
  209. }
  210. return obj[_class] = {
  211. * find(query, projection, cursorCalls={}){
  212. let cursor = db.collection(_class).find(query, projection)
  213. for (let [method, params] of Object.entries(cursorCalls)){
  214. if (typeof cursor[method] !== "function"){
  215. throw new SyntaxError(`Wrong cursor method ${method}`)
  216. }
  217. cursor = cursor[method](...params)
  218. }
  219. let cursorGen = asynchronize({s: cursor.stream(),
  220. chunkEventName: 'data',
  221. endEventName: 'close'})
  222. for (const pObj of cursorGen()){
  223. yield new Promise((ok, fail) =>
  224. pObj.then(obj => (/*console.log(obj),*/ok(Savable.newSavable(obj, null, false))),
  225. err => fail(err)))
  226. }
  227. },
  228. async findOne(query, projection){
  229. let result = await db.collection(_class).findOne(query, projection)
  230. if (result)
  231. return Savable.newSavable(result, null, false)
  232. return result
  233. }
  234. }
  235. },
  236. set(obj, propName, value){
  237. }
  238. })
  239. }
  240. static get relations(){
  241. //empty default relations, acceptable: {field: foreignField}, where:
  242. //field and foreign field can be Savable, Array or Set
  243. //both fields can be specified as "field", "field.subfield"
  244. //or field: {subfield: foreignField} //TODO later if needed
  245. //TODO: move it into object instead of class to give more flexibility, for example
  246. //if person has children, it can have backRef father or mother depending on sex:
  247. //return {
  248. // children: this.sex === 'male' ? 'father': 'mother'
  249. //}
  250. return {}
  251. }
  252. }
  253. Savable.classes = {Savable}
  254. /**
  255. * sliceSavable - slice (limit) Savables for some permission
  256. * Array userACL - array of objectIDs, words or savable refs - current user, group objectid, or `tags` or `role` (ACL)
  257. */
  258. function sliceSavable(userACL){
  259. userACL = userACL.map(tag => tag.toString())
  260. console.log(userACL)
  261. class SlicedSavable extends Savable {
  262. constructor(...params){
  263. super (...params)
  264. if (!this._empty){
  265. this.___permissionsPrepare()
  266. }
  267. }
  268. ___permissionsPrepare(){
  269. if (this._empty) return
  270. if (!this.___permissions) this.___permissions = {}
  271. for (let [perm, acl] of Object.entries(this.__proto__.constructor.defaultPermissions)){
  272. if (!this.___permissions[perm]){
  273. this.___permissions[perm] = [...acl]
  274. }
  275. }
  276. }
  277. ___permissionCan(permission, permissions=this.___permissions, obj=this){
  278. const acl = (permissions &&
  279. permissions[permission] ||
  280. this.__proto__.constructor.defaultPermissions[permission]).map(tag => tag.toString())
  281. if (acl.includes('owner') && obj.___owner && userACL.includes(obj.___owner.toString())){
  282. return true
  283. }
  284. for (let uTag of userACL){
  285. if (acl.includes(uTag)){
  286. return true
  287. }
  288. }
  289. return false
  290. }
  291. populate(obj){ //place to check read permission
  292. console.log(obj)
  293. if (!this.___permissionCan('read', obj.___permissions, obj)){
  294. throw new ReferenceError(`No Access To Entity ${this._id} of class ${this._class}`)
  295. }
  296. super.populate(obj)
  297. }
  298. async save(...params){
  299. if (!this._id && !this.___permissionCan('create'))
  300. throw new ReferenceError(`Permissison denied Create Entity of class ${this._class}`)
  301. if (this._id && !this.___permissionCan('write'))
  302. throw new ReferenceError(`Permissison denied Save Entity ${this._id} of class ${this._class}`)
  303. if (!this._id){
  304. this.___owner = userACL[0] //TODO fix objectid troubles
  305. console.log(typeof this.___owner, this.___owner)
  306. }
  307. return await super.save(...params)
  308. }
  309. async delete(noRefs=false){
  310. if (!this.___permissionCan('delete'))
  311. throw new ReferenceError(`Permissison denied Delete Entity ${this._id} of class ${this._class}`)
  312. return await super.delete(noRefs)
  313. }
  314. static ___permissionQuery(permission){
  315. //const withObjectIDs = userACL.map((a,id) => (id = new ObjectID(a)) && id.toString() === a ? id : a)
  316. const withObjectIDs = userACL
  317. return {
  318. $or: [
  319. {[`___permissions.${permission}`]: {$in: withObjectIDs}},
  320. {$and: [{[`___permissions.${permission}`]: "owner"},
  321. {___owner: userACL[0]}]}]
  322. }
  323. }
  324. static get m() {
  325. return new Proxy({}, {
  326. get(obj, _class){
  327. if (_class in obj){
  328. return obj[_class]
  329. }
  330. return obj[_class] = {
  331. * find(query, projection, cursorCalls={}){
  332. Savable.addClass(_class)
  333. let permittedQuery = {$and: [SlicedSavable.___permissionQuery('read') ,query]}
  334. // console.log(JSON.stringify(permittedQuery, null, 4))
  335. yield* Savable.m[_class].find(permittedQuery, projection, cursorCalls)
  336. },
  337. async findOne(query, projection){
  338. Savable.addClass(_class)
  339. let permittedQuery = {$and: [SlicedSavable.___permissionQuery('read') ,query]}
  340. return await Savable.m[_class].findOne(permittedQuery, projection)
  341. }
  342. }
  343. },
  344. set(obj, propName, value){
  345. }
  346. })
  347. }
  348. static get defaultPermissions(){
  349. return {
  350. //savable refs, objectid's, words like 'tags' or 'roles'
  351. read: ['owner', 'user'],
  352. write: ['owner', 'admin'],
  353. create: ['user'],
  354. delete: ['admin'],
  355. /*permission
  356. * TODO: permissions for read and write permissions
  357. *
  358. */
  359. }
  360. }
  361. }
  362. return SlicedSavable
  363. }
  364. return {Savable, sliceSavable}
  365. }