index.js 24 KB

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