index.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. const { MongoClient, ObjectID } = require("mongodb");
  2. const {asynchronize, openPromise } = require('./asynchronize')
  3. const mm = db => {
  4. class Savable {
  5. backupRelations(){
  6. this._loadRelations = {};
  7. for (const relation in this.__proto__.constructor.relations){
  8. this._loadRelations[relation] = this[relation] instanceof Array ? [...this[relation]] : this[relation]
  9. }
  10. console.log('DIFF SHOW')
  11. }
  12. populate(obj){
  13. const convertSavables = (obj) => {
  14. for (const key in obj){
  15. if (Savable.isSavable(obj[key])){
  16. obj[key] = (this._ref &&
  17. Savable.equals(obj[key], this._ref)) ?
  18. this._ref :
  19. Savable.newSavable(obj[key], this)
  20. }
  21. else if (typeof obj[key] === 'object'){
  22. convertSavables(obj[key])
  23. }
  24. }
  25. }
  26. Object.assign(this, obj)
  27. convertSavables(this)
  28. this.backupRelations()
  29. //this._id = obj._id
  30. }
  31. get _empty(){
  32. return !!this.then
  33. }
  34. set _empty(value){
  35. if (value){
  36. //TODO: list of callbacks, because then can be called many times, and
  37. //it's not reason to repeat query to db
  38. this.then = (cb, err) => {
  39. if (!this._id) err(new ReferenceError('Id is empty'))
  40. if (!this._class) err(new ReferenceError('Class is empty'))
  41. const promise = openPromise()
  42. this.collection.findOne(this._id).then( data => {
  43. if (!data){
  44. let error = new ReferenceError('Document Not Found')
  45. if (typeof err === 'function') err(error)
  46. else promise.reject(error)
  47. }
  48. else {
  49. delete this.then
  50. this.populate(data)
  51. if (typeof cb === 'function')
  52. promise.resolve(cb(this))
  53. else {
  54. promise.resolve(this)
  55. }
  56. }
  57. })
  58. return promise
  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(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. for (const relation in this.__proto__.constructor.relations){
  86. let backRef = this.__proto__.constructor.relations[relation]
  87. if (Array.isArray(backRef)) backRef = backRef[0]
  88. const loadRelation = this._loadRelations[relation]
  89. const loadRelationAsArray = loadRelation instanceof Savable ? [loadRelation] : loadRelation
  90. let {value, obj, lastKey: key} = await getValueByField(relation, this)
  91. const valueAsArray = value instanceof Savable ? [value] : value
  92. if (loadRelationAsArray){ //check for removed Refs
  93. const removedRefs = valueAsArray ?
  94. loadRelationAsArray.filter(ref => !Savable.existsInArray(valueAsArray, ref)) :
  95. loadRelationAsArray
  96. for (const ref of removedRefs){
  97. try { await ref } catch (e) {console.log('SYNC RELATIONS REMOVE ERROR') }
  98. await ref.removeRelation(this, relation)
  99. }
  100. }
  101. if (valueAsArray){ //check for added refs
  102. for (const foreignSavable of valueAsArray) {
  103. try { await foreignSavable } catch (e) {console.log('SYNC RELATIONS ADD ERROR') }
  104. let foreignLoadRelationsAsArray = Savable.arrize(foreignSavable._loadRelations[backRef])
  105. if (foreignSavable && !Savable.existsInArray(foreignLoadRelationsAsArray, this)){
  106. await foreignSavable.setRelation(this, relation)
  107. }
  108. }
  109. }
  110. }
  111. }
  112. async function recursiveSlicer(obj){
  113. let result = obj instanceof Array ? [] : {}
  114. for (const key in obj){
  115. if (obj[key] && typeof obj[key] === 'object'){
  116. if (obj[key] instanceof Savable){
  117. if (!(obj[key]._id)){
  118. await obj[key].save().catch(err => console.log('ERR', err))
  119. }
  120. result[key] = obj[key].shortData()
  121. }
  122. else {
  123. result[key] = await recursiveSlicer(obj[key])
  124. }
  125. }
  126. else {
  127. result[key] = obj[key]
  128. }
  129. }
  130. return result;
  131. }
  132. const {_id, _empty, _ref, _loadRelations, then, ...toSave} = await recursiveSlicer(this)
  133. //TODO: UPSERT
  134. if (!this._id){ //first time
  135. const { insertedId } = await this.collection.insertOne(toSave)
  136. this._id = insertedId
  137. }
  138. else { //update
  139. await this.collection.updateOne({_id: this._id}, {$set: toSave}).catch(err => console.log('UPDATE ERR', err))
  140. }
  141. await syncRelations()
  142. this.backupRelations()
  143. return this
  144. }
  145. // method to get ref snapshot (empty object with some data). gives optimizations in related objects
  146. // place for permission, owner, probably short relations
  147. shortData(){
  148. const {_id, _class} = this
  149. return { _id, _class }
  150. }
  151. async setRelation(ref, refRelationName){
  152. await this
  153. const ourRelation = ref.__proto__.constructor.relations[refRelationName]
  154. const ourArray = ourRelation instanceof Array
  155. const ourRelationName = ourArray ? ourRelation[0] : ourRelation
  156. let shortQuery = {[ourRelationName]: ref.shortData()}
  157. let query;
  158. if (ourArray || this[ourRelationName] instanceof Array){
  159. this[ourRelationName] = this[ourRelationName] || []
  160. this[ourRelationName] = this[ourRelationName] instanceof Array ? this[ourRelationName] : [this[ourRelationName]]
  161. if (Savable.existsInArray(this[ourRelationName], ref)) {
  162. this[ourRelationName].push(ref)
  163. this._id && this._loadRelations[ourRelationName].push(ref)
  164. }
  165. query = {$addToSet: shortQuery}
  166. }
  167. else {
  168. this[ourRelationName] = ref
  169. this._id && (this._loadRelations[ourRelationName] = ref)
  170. query = {$set: shortQuery}
  171. }
  172. console.log('SET RELATION:', query)
  173. if (this._id){
  174. console.log('SET RELATION:', query)
  175. await this.collection.updateOne({_id: this._id}, query).catch(err => console.log('UPDATE ERR', err))
  176. }
  177. }
  178. async removeRelation(ref, refRelationName){ //i. e. this = child, ref = parent object, refRelationName = children in parent
  179. await this
  180. const ourRelation = ref.__proto__.constructor.relations[refRelationName]
  181. const ourArray = ourRelation instanceof Array
  182. const ourRelationName = ourArray ? ourRelation[0] : ourRelation
  183. if (this._id){
  184. const query = ourArray ? {$pull: {[ourRelationName]: ref.shortData()}}
  185. : {$set: {[ourRelationName]: null}}
  186. console.log('REMOVE RELATION:', query)
  187. await this.collection.updateOne({_id: this._id}, query).catch(err => console.log('UPDATE ERR', err))
  188. }
  189. (this[ourRelationName] instanceof Array) ? this._loadRelations[ourRelationName] = this[ourRelationName] = this[ourRelationName].filter(ourRef => !ourRef.equals(ref))
  190. : this[ourRelationName] = null;
  191. }
  192. async delete(noRefs=false){
  193. if (!noRefs) for (const relation in this.__proto__.constructor.relations){
  194. const backRef = this.__proto__.constructor.relations[relation]
  195. const loadRelation = this._loadRelations && this._loadRelations[relation]
  196. const loadRelationAsArray = loadRelation instanceof Savable ? [loadRelation] : loadRelation
  197. if (loadRelationAsArray){
  198. for (const ref of loadRelationAsArray){
  199. try {
  200. await ref
  201. }
  202. catch (e) {console.log('DELETE SYNC RELATIONS ERROR') }
  203. await ref.removeRelation(this, relation)
  204. }
  205. }
  206. }
  207. const id = this._id
  208. const col = this._class && this.collection
  209. for (let key in this)
  210. delete this[key]
  211. delete this.__proto__
  212. if (col)
  213. return await col.deleteOne({_id: id})
  214. }
  215. static arrize(value){
  216. if (Array.isArray(value)) return value
  217. if (value) return [value]
  218. return []
  219. }
  220. static equals(obj1, obj2){
  221. if (!obj1 || !obj2) return false
  222. if(!obj1._id) return obj1 === obj2
  223. if(!obj2._id) return obj1 === obj2
  224. return obj1._id.toString() === obj2._id.toString()
  225. }
  226. equals(obj){
  227. return Savable.equals(this, obj)
  228. }
  229. static existsInArray(arr, obj){
  230. if (!Array.isArray(arr)) return false
  231. let filtered = arr.filter(item => Savable.equals(item, obj))
  232. return filtered.length
  233. }
  234. static isSavable(obj){
  235. return obj && obj._id && obj._class
  236. }
  237. static newSavable(obj, ref, empty=true){
  238. let className = obj._class || "Savable"
  239. className = Savable.classes[className] ? className : "Savable"
  240. if (obj.__proto__.constructor === Savable.classes[className]){
  241. return obj
  242. }
  243. return new Savable.classes[className](obj, ref, empty)
  244. }
  245. static addClass(_class){ //explicit method to add class to Savable registry for instantiate right class later
  246. (typeof _class == 'function') && (Savable.classes[_class.name] = _class)
  247. }
  248. static get m(){
  249. return new Proxy({}, {
  250. get(obj, _class){
  251. if (_class in obj){
  252. return obj[_class]
  253. }
  254. const applyCursorCalls = (cursor, calls) =>{
  255. if (!calls) return cursor;
  256. for (let [method, params] of Object.entries(calls)){
  257. if (typeof cursor[method] !== "function"){
  258. throw new SyntaxError(`Wrong cursor method ${method}`)
  259. }
  260. cursor = cursor[method](...params)
  261. }
  262. return cursor;
  263. }
  264. return obj[_class] = {
  265. * find(query, cursorCalls={}){
  266. let cursor = applyCursorCalls(db.collection(_class).find(query), cursorCalls)
  267. let cursorGen = asynchronize({s: cursor.stream(),
  268. chunkEventName: 'data',
  269. endEventName: 'close',
  270. errEventName: 'error',
  271. countMethodName: 'count'})
  272. for (const pObj of cursorGen()){
  273. yield new Promise((ok, fail) =>
  274. pObj.then(obj => (/*console.log(obj),*/ok(Savable.newSavable(obj, null, false))),
  275. err => fail(err)))
  276. }
  277. },
  278. async count(query, cursorCalls={}){
  279. let cursor = applyCursorCalls(db.collection(_class).find(query), cursorCalls)
  280. return await cursor.count(true)
  281. },
  282. async findOne(query){
  283. let result = await db.collection(_class).findOne(query)
  284. if (result)
  285. return Savable.newSavable(result, null, false)
  286. return result
  287. }
  288. }
  289. },
  290. set(obj, propName, value){
  291. }
  292. })
  293. }
  294. static get relations(){
  295. //empty default relations, acceptable: {field: foreignField}, where:
  296. //field and foreign field can be Savable, Array or Set
  297. //both fields can be specified as "field", "field.subfield"
  298. //or field: {subfield: foreignField} //TODO later if needed
  299. //TODO: move it into object instead of class to give more flexibility, for example
  300. //if person has children, it can have backRef father or mother depending on sex:
  301. //return {
  302. // children: this.sex === 'male' ? 'father': 'mother'
  303. //}
  304. //
  305. //return {
  306. // parent: ["children"],
  307. // notebooks: "owner"
  308. //}
  309. return {}
  310. }
  311. }
  312. Savable.classes = {Savable}
  313. /**
  314. * sliceSavable - slice (limit) Savables for some permission
  315. * Array userACL - array of objectIDs, words or savable refs - current user, group objectid, or `tags` or `role` (ACL)
  316. */
  317. function sliceSavable(userACL){
  318. userACL = userACL.map(tag => tag.toString())
  319. //console.log(userACL)
  320. class SlicedSavable extends Savable {
  321. constructor(...params){
  322. super (...params)
  323. if (!this._empty){
  324. this.___permissionsPrepare()
  325. }
  326. }
  327. ___permissionsPrepare(){
  328. if (this._empty) return
  329. if (!this.___permissions) this.___permissions = {}
  330. for (let [perm, acl] of Object.entries(this.__proto__.constructor.defaultPermissions)){
  331. if (!this.___permissions[perm]){
  332. this.___permissions[perm] = [...acl]
  333. }
  334. }
  335. }
  336. ___permissionCan(permission, permissions=this.___permissions, obj=this){
  337. const acl = (permissions &&
  338. permissions[permission] ||
  339. this.__proto__.constructor.defaultPermissions[permission]).map(tag => tag.toString())
  340. if (!this._id && permission === 'read') return true; //if new entity you can anything
  341. if (acl.includes('owner') && obj.___owner && userACL.includes(obj.___owner.toString())){
  342. return true
  343. }
  344. for (let uTag of userACL){
  345. if (acl.includes(uTag)){
  346. return true
  347. }
  348. }
  349. return false
  350. }
  351. populate(obj){ //place to check read permission
  352. //console.log(obj)
  353. if (!this.___permissionCan('read', obj.___permissions, obj)){
  354. throw new ReferenceError(`No Access To Entity ${this._id} of class ${this._class}`)
  355. }
  356. super.populate(obj)
  357. }
  358. async save(noSync=false){
  359. if (!this._id && !this.___permissionCan('create'))
  360. throw new ReferenceError(`Permission denied Create Entity of class ${this._class}`)
  361. if (this._id && !this.___permissionCan('write'))
  362. throw new ReferenceError(`Permission denied Save Entity ${this._id} of class ${this._class}`)
  363. if (!this._id){
  364. this.___owner = userACL[0] //TODO fix objectid troubles
  365. //console.log(typeof this.___owner, this.___owner)
  366. }
  367. return await super.save(noSync)
  368. }
  369. async setRelation(ref, refRelationName){
  370. await this
  371. const ourRelation = ref.__proto__.constructor.relations[refRelationName]
  372. const ourArray = ourRelation instanceof Array
  373. const ourRelationName = ourArray ? ourRelation[0] : ourRelation
  374. if (!this._id || this.___permissionCan('write') ||
  375. (this.__proto__.constructor.guestRelations.includes(ourRelationName) && this.___permissionCan('read')))
  376. return await super.setRelation(ref, refRelationName)
  377. throw new ReferenceError(`Permission denied Set Relation Entity ${this._id} of class ${this._class} ref: ${ref._id} of class ${ref._class}`)
  378. }
  379. async removeRelation(ref, refRelationName){
  380. await this;
  381. const ourRelation = ref.__proto__.constructor.relations[refRelationName]
  382. const ourArray = ourRelation instanceof Array
  383. const ourRelationName = ourArray ? ourRelation[0] : ourRelation
  384. if (!this._id || this.___permissionCan('write') ||
  385. (this.__proto__.constructor.guestRelations.includes(ourRelationName) && this.___permissionCan('read')))
  386. return await super.removeRelation(ref, refRelationName)
  387. throw new ReferenceError(`Permission denied Remove Relation Entity ${this._id} of class ${this._class} ref: ${ref._id} of class ${ref._class}`)
  388. }
  389. async delete(noRefs=false){
  390. if (!this.___permissionCan('delete'))
  391. throw new ReferenceError(`Permission denied Delete Entity ${this._id} of class ${this._class}`)
  392. return await super.delete(noRefs)
  393. }
  394. static ___permissionQuery(permission){
  395. //const withObjectIDs = userACL.map((a,id) => (id = new ObjectID(a)) && id.toString() === a ? id : a)
  396. const withObjectIDs = userACL
  397. return {
  398. $or: [
  399. {[`___permissions.${permission}`]: {$in: withObjectIDs}},
  400. {$and: [{[`___permissions.${permission}`]: "owner"},
  401. {___owner: userACL[0]}]}]
  402. }
  403. }
  404. static get m() {
  405. return new Proxy({}, {
  406. get(obj, _class){
  407. if (_class in obj){
  408. return obj[_class]
  409. }
  410. return obj[_class] = {
  411. * find(query, cursorCalls={}){
  412. const originalClass = Savable.classes[_class]
  413. Savable.addClass(SlicedSavable.classes[_class])
  414. let permittedQuery = {$and: [SlicedSavable.___permissionQuery('read') ,query]}
  415. //console.log(JSON.stringify(permittedQuery, null, 4))
  416. let iter = Savable.m[_class].find(permittedQuery, cursorCalls)
  417. Savable.addClass(originalClass)
  418. yield* iter;
  419. },
  420. async count(query, cursorCalls={}){
  421. let permittedQuery = {$and: [SlicedSavable.___permissionQuery('read') ,query]}
  422. return await Savable.m[_class].count(permittedQuery, cursorCalls)
  423. },
  424. async findOne(query){
  425. const originalClass = Savable.classes[_class]
  426. Savable.addClass(SlicedSavable.classes[_class])
  427. const permittedQuery = {$and: [SlicedSavable.___permissionQuery('read') ,query]}
  428. const p = Savable.m[_class].findOne(permittedQuery)
  429. Savable.addClass(originalClass)
  430. return await p;
  431. }
  432. }
  433. },
  434. set(obj, propName, value){
  435. }
  436. })
  437. }
  438. static get defaultPermissions(){
  439. return {
  440. //savable refs, objectid's, words like 'tags' or 'roles'
  441. read: ['owner', 'user'],
  442. write: ['owner', 'admin'],
  443. create: ['user'],
  444. delete: ['admin'],
  445. /*permission
  446. * TODO: permissions for read and write permissions
  447. *
  448. */
  449. }
  450. }
  451. static get guestRelations(){ //guest relations are accessible to write by setRelation or removeRelation even if no write permission, only with read
  452. return []
  453. }
  454. }
  455. return SlicedSavable
  456. }
  457. return {Savable, sliceSavable}
  458. }
  459. async function connect(dbName, dsn="mongodb://localhost:27017/"){
  460. if (!dbName)
  461. throw new ReferenceError(`db name does not provided`)
  462. const mongoClient = new MongoClient(dsn, { useNewUrlParser: true });
  463. const client = await mongoClient.connect()
  464. const db = client.db(dbName)
  465. const {Savable, sliceSavable: slice} = mm(db)
  466. return {
  467. Savable,
  468. slice,
  469. }
  470. }
  471. module.exports = {
  472. mm,
  473. connect
  474. }