mm.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. const ObjectID = require("mongodb").ObjectID;
  2. const asynchronize = require('./asynchronize').asynchronize
  3. module.exports = db => {
  4. class Savable {
  5. constructor(obj, ref, empty=false){
  6. this._id = null
  7. this._ref = ref
  8. this._class = this.__proto__.constructor.name
  9. this._empty = true
  10. Savable.addClass(this.__proto__.constructor)
  11. if (obj){
  12. this.populate(obj)
  13. this._empty = empty
  14. }
  15. }
  16. saveRelations(){
  17. this._loadRelations = {};
  18. for (const relation in this.__proto__.constructor.relations){
  19. this._loadRelations[relation] = this[relation] instanceof Array ? [...this[relation]] : this[relation]
  20. }
  21. }
  22. populate(obj){
  23. const convertSavables = (obj) => {
  24. for (const key in obj){
  25. if (Savable.isSavable(obj[key])){
  26. obj[key] = (this._ref &&
  27. obj[key]._id.toString() == this._ref._id.toString()) ?
  28. this._ref :
  29. Savable.newSavable(obj[key], this)
  30. }
  31. else if (typeof obj[key] === 'object'){
  32. convertSavables(obj[key])
  33. }
  34. }
  35. }
  36. Object.assign(this, obj)
  37. convertSavables(this)
  38. this.saveRelations()
  39. //this._id = obj._id
  40. }
  41. get _empty(){
  42. return !!this.then
  43. }
  44. set _empty(value){
  45. if (value){
  46. this.then = (cb, err) => {
  47. let stamp = (new Date()).getTime()
  48. delete this.then
  49. if (!this._id) err(new ReferenceError('Id is empty'))
  50. if (!this._class) err(new ReferenceError('Class is empty'))
  51. this.collection.findOne(this._id).then( data => {
  52. if (!data){
  53. err(new ReferenceError('Document Not Found'))
  54. }
  55. this.populate(data)
  56. cb(this)
  57. })
  58. return this
  59. }
  60. }
  61. else {
  62. delete this.then
  63. }
  64. }
  65. get createdAt(){
  66. return this._id ? new Date(this._id.getTimestamp()) : null
  67. }
  68. get collection(){
  69. return db.collection(this._class)
  70. }
  71. async save(noRefs=false, noSync=false){
  72. if (this.empty) return this;
  73. const syncRelations = async () => {
  74. if (noSync) return
  75. if (!(this && this.__proto__ && this.__proto__.constructor && this.__proto__.constructor.relations)) return
  76. async function getValueByField(field, savable) {
  77. let path = field.split('.');
  78. await savable//.catch(e => console.log('GET VALUE BY FIELD ERROR'));
  79. let result = savable;
  80. let prev;
  81. let lastKey = path.pop()
  82. while (prev = result, result = result[path.shift()] && path.length);
  83. return {value: prev[lastKey], obj: prev, lastKey};
  84. }
  85. let setBackRef = async (backRef, foreignSavable) => {
  86. const {value: backRefValue,
  87. obj: backRefObj,
  88. lastKey: backRefKey} = await getValueByField(backRef, foreignSavable)
  89. if (backRefValue instanceof Array){
  90. if (!backRefValue.includes(this)){
  91. backRefValue.push(this)
  92. }
  93. }
  94. else {
  95. backRefObj[backRefKey] = this
  96. }
  97. noRefs || await foreignSavable.save(true)
  98. }
  99. for (const relation in this.__proto__.constructor.relations){
  100. const backRef = this.__proto__.constructor.relations[relation]
  101. const loadRelation = this._loadRelations[relation]
  102. const loadRelationAsArray = loadRelation instanceof Savable ? [loadRelation] : loadRelation
  103. let {value, obj, lastKey: key} = await getValueByField(relation, this)
  104. const valueAsArray = value instanceof Savable ? [value] : value
  105. if (loadRelationAsArray){
  106. const removedRefs = valueAsArray ? loadRelationAsArray.filter(ref => !valueAsArray.includes(ref)) : loadRelationAsArray
  107. for (const ref of removedRefs){
  108. try {
  109. await ref
  110. }
  111. catch (e) {console.log('SYNC RELATIONS ERROR') }
  112. if (ref[backRef] instanceof Array){
  113. ref[backRef] = ref[backRef].filter(br => br._id !== this._id)
  114. }
  115. else {
  116. ref[backRef] = null
  117. }
  118. noRefs || await ref.save(true)
  119. }
  120. }
  121. if (valueAsArray){
  122. for (const foreignSavable of valueAsArray){
  123. await setBackRef(backRef, foreignSavable)
  124. }
  125. }
  126. }
  127. }
  128. async function recursiveSlicer(obj){
  129. let result = obj instanceof Array ? [] : {}
  130. for (const key in obj){
  131. if (obj[key] && typeof obj[key] === 'object'){
  132. if (obj[key] instanceof Savable){
  133. if (!(obj[key]._id)){
  134. await obj[key].save().catch(err => console.log('ERR', err))
  135. }
  136. result[key] = {_id: obj[key]._id, _class: obj[key]._class}
  137. }
  138. else {
  139. result[key] = await recursiveSlicer(obj[key])
  140. }
  141. }
  142. else {
  143. result[key] = obj[key]
  144. }
  145. }
  146. return result;
  147. }
  148. const {_id, _empty, _ref, _loadRelations, then, ...toSave} = await recursiveSlicer(this)
  149. //TODO: UPSERT
  150. if (!this._id){ //first time
  151. const { insertedId } = await this.collection.insertOne(toSave)
  152. this._id = insertedId
  153. }
  154. else { //update
  155. await this.collection.updateOne({_id: this._id}, {$set: toSave}).catch(err => console.log('UPDATE ERR', err))
  156. }
  157. await syncRelations()
  158. this.saveRelations()
  159. return this
  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. (typeof _class == 'function') && (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 => (/*console.log(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, obj=this){
  277. const acl = (permissions &&
  278. permissions[permission] ||
  279. this.__proto__.constructor.defaultPermissions[permission]).map(tag => tag.toString())
  280. if (acl.includes('owner') && obj.___owner && userACL.includes(obj.___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. //console.log(obj)
  292. if (!this.___permissionCan('read', obj.___permissions, obj)){
  293. throw new ReferenceError(`No Access To Entity ${this._id} of class ${this._class}`)
  294. }
  295. super.populate(obj)
  296. }
  297. async save(...params){
  298. if (!this._id && !this.___permissionCan('create'))
  299. throw new ReferenceError(`Permissison denied Create Entity of class ${this._class}`)
  300. if (this._id && !this.___permissionCan('write'))
  301. throw new ReferenceError(`Permissison denied Save Entity ${this._id} of class ${this._class}`)
  302. if (!this._id){
  303. this.___owner = userACL[0] //TODO fix objectid troubles
  304. console.log(typeof this.___owner, this.___owner)
  305. }
  306. return await super.save(...params)
  307. }
  308. async delete(noRefs=false){
  309. if (!this.___permissionCan('delete'))
  310. throw new ReferenceError(`Permissison denied Delete Entity ${this._id} of class ${this._class}`)
  311. return await super.delete(noRefs)
  312. }
  313. static ___permissionQuery(permission){
  314. //const withObjectIDs = userACL.map((a,id) => (id = new ObjectID(a)) && id.toString() === a ? id : a)
  315. const withObjectIDs = userACL
  316. return {
  317. $or: [
  318. {[`___permissions.${permission}`]: {$in: withObjectIDs}},
  319. {$and: [{[`___permissions.${permission}`]: "owner"},
  320. {___owner: userACL[0]}]}]
  321. }
  322. }
  323. static get m() {
  324. return new Proxy({}, {
  325. get(obj, _class){
  326. if (_class in obj){
  327. return obj[_class]
  328. }
  329. return obj[_class] = {
  330. * find(query, projection, cursorCalls={}){
  331. const originalClass = Savable.classes[_class.name]
  332. Savable.addClass(_class)
  333. let permittedQuery = {$and: [SlicedSavable.___permissionQuery('read') ,query]}
  334. let iter = Savable.m[_class].find(permittedQuery, projection, cursorCalls)
  335. Savable.addClass(originalClass)
  336. yield* iter;
  337. },
  338. async findOne(query, projection){
  339. const originalClass = Savable.classes[_class.name]
  340. Savable.addClass(_class)
  341. const permittedQuery = {$and: [SlicedSavable.___permissionQuery('read') ,query]}
  342. const p = Savable.m[_class].findOne(permittedQuery, projection)
  343. Savable.addClass(originalClass)
  344. return await p;
  345. }
  346. }
  347. },
  348. set(obj, propName, value){
  349. }
  350. })
  351. }
  352. static get defaultPermissions(){
  353. return {
  354. //savable refs, objectid's, words like 'tags' or 'roles'
  355. read: ['owner', 'user'],
  356. write: ['owner', 'admin'],
  357. create: ['user'],
  358. delete: ['admin'],
  359. /*permission
  360. * TODO: permissions for read and write permissions
  361. *
  362. */
  363. }
  364. }
  365. }
  366. return SlicedSavable
  367. }
  368. return {Savable, sliceSavable}
  369. }