index.js 26 KB

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