index.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. errEventName: 'error',
  222. countMethodName: 'count'})
  223. for (const pObj of cursorGen()){
  224. yield new Promise((ok, fail) =>
  225. pObj.then(obj => (/*console.log(obj),*/ok(Savable.newSavable(obj, null, false))),
  226. err => fail(err)))
  227. }
  228. },
  229. async findOne(query, projection){
  230. let result = await db.collection(_class).findOne(query, projection)
  231. if (result)
  232. return Savable.newSavable(result, null, false)
  233. return result
  234. }
  235. }
  236. },
  237. set(obj, propName, value){
  238. }
  239. })
  240. }
  241. static get relations(){
  242. //empty default relations, acceptable: {field: foreignField}, where:
  243. //field and foreign field can be Savable, Array or Set
  244. //both fields can be specified as "field", "field.subfield"
  245. //or field: {subfield: foreignField} //TODO later if needed
  246. //TODO: move it into object instead of class to give more flexibility, for example
  247. //if person has children, it can have backRef father or mother depending on sex:
  248. //return {
  249. // children: this.sex === 'male' ? 'father': 'mother'
  250. //}
  251. return {}
  252. }
  253. }
  254. Savable.classes = {Savable}
  255. /**
  256. * sliceSavable - slice (limit) Savables for some permission
  257. * Array userACL - array of objectIDs, words or savable refs - current user, group objectid, or `tags` or `role` (ACL)
  258. */
  259. function sliceSavable(userACL){
  260. userACL = userACL.map(tag => tag.toString())
  261. //console.log(userACL)
  262. class SlicedSavable extends Savable {
  263. constructor(...params){
  264. super (...params)
  265. if (!this._empty){
  266. this.___permissionsPrepare()
  267. }
  268. }
  269. ___permissionsPrepare(){
  270. if (this._empty) return
  271. if (!this.___permissions) this.___permissions = {}
  272. for (let [perm, acl] of Object.entries(this.__proto__.constructor.defaultPermissions)){
  273. if (!this.___permissions[perm]){
  274. this.___permissions[perm] = [...acl]
  275. }
  276. }
  277. }
  278. ___permissionCan(permission, permissions=this.___permissions, obj=this){
  279. const acl = (permissions &&
  280. permissions[permission] ||
  281. this.__proto__.constructor.defaultPermissions[permission]).map(tag => tag.toString())
  282. if (acl.includes('owner') && obj.___owner && userACL.includes(obj.___owner.toString())){
  283. return true
  284. }
  285. for (let uTag of userACL){
  286. if (acl.includes(uTag)){
  287. return true
  288. }
  289. }
  290. return false
  291. }
  292. populate(obj){ //place to check read permission
  293. //console.log(obj)
  294. if (!this.___permissionCan('read', obj.___permissions, obj)){
  295. throw new ReferenceError(`No Access To Entity ${this._id} of class ${this._class}`)
  296. }
  297. super.populate(obj)
  298. }
  299. async save(noRefs=false, noSync=false){
  300. if (!this._id && !this.___permissionCan('create'))
  301. throw new ReferenceError(`Permissison denied Create Entity of class ${this._class}`)
  302. if (this._id && !this.___permissionCan('write') && !noRefs) //give ability to change backrefs for not permitted records
  303. throw new ReferenceError(`Permissison denied Save Entity ${this._id} of class ${this._class}`)
  304. if (!this._id){
  305. this.___owner = userACL[0] //TODO fix objectid troubles
  306. //console.log(typeof this.___owner, this.___owner)
  307. }
  308. return await super.save(noRefs, noSync)
  309. }
  310. async delete(noRefs=false){
  311. if (!this.___permissionCan('delete'))
  312. throw new ReferenceError(`Permissison denied Delete Entity ${this._id} of class ${this._class}`)
  313. return await super.delete(noRefs)
  314. }
  315. static ___permissionQuery(permission){
  316. //const withObjectIDs = userACL.map((a,id) => (id = new ObjectID(a)) && id.toString() === a ? id : a)
  317. const withObjectIDs = userACL
  318. return {
  319. $or: [
  320. {[`___permissions.${permission}`]: {$in: withObjectIDs}},
  321. {$and: [{[`___permissions.${permission}`]: "owner"},
  322. {___owner: userACL[0]}]}]
  323. }
  324. }
  325. static get m() {
  326. return new Proxy({}, {
  327. get(obj, _class){
  328. if (_class in obj){
  329. return obj[_class]
  330. }
  331. return obj[_class] = {
  332. * find(query, projection, cursorCalls={}){
  333. const originalClass = Savable.classes[_class]
  334. Savable.addClass(SlicedSavable.classes[_class])
  335. let permittedQuery = {$and: [SlicedSavable.___permissionQuery('read') ,query]}
  336. //console.log(JSON.stringify(permittedQuery, null, 4))
  337. let iter = Savable.m[_class].find(permittedQuery, projection, cursorCalls)
  338. Savable.addClass(originalClass)
  339. yield* iter;
  340. },
  341. async findOne(query, projection){
  342. const originalClass = Savable.classes[_class]
  343. Savable.addClass(SlicedSavable.classes[_class])
  344. const permittedQuery = {$and: [SlicedSavable.___permissionQuery('read') ,query]}
  345. const p = Savable.m[_class].findOne(permittedQuery, projection)
  346. Savable.addClass(originalClass)
  347. return await p;
  348. }
  349. }
  350. },
  351. set(obj, propName, value){
  352. }
  353. })
  354. }
  355. static get defaultPermissions(){
  356. return {
  357. //savable refs, objectid's, words like 'tags' or 'roles'
  358. read: ['owner', 'user'],
  359. write: ['owner', 'admin'],
  360. create: ['user'],
  361. delete: ['admin'],
  362. /*permission
  363. * TODO: permissions for read and write permissions
  364. *
  365. */
  366. }
  367. }
  368. }
  369. return SlicedSavable
  370. }
  371. return {Savable, sliceSavable}
  372. }