index.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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. }
  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. Savable.equals(obj[key], this._ref)) ?
  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.backupRelations()
  39. //this._id = obj._id
  40. }
  41. get _empty(){
  42. return !!this.then
  43. }
  44. set _empty(value){
  45. if (value){
  46. //TODO: list of callbacks, because then can be called many times, and
  47. //it's not reason to repeat query to db
  48. this.then = (cb, err) => {
  49. if (!this._id) err(new ReferenceError('Id is empty'))
  50. if (!this._class) err(new ReferenceError('Class is empty'))
  51. const promise = openPromise()
  52. this.collection.findOne(this._id).then( data => {
  53. if (!data){
  54. let error = new ReferenceError('Document Not Found')
  55. if (typeof err === 'function') err(error)
  56. else promise.reject(error)
  57. }
  58. else {
  59. delete this.then
  60. this.populate(data)
  61. if (typeof cb === 'function')
  62. promise.resolve(cb(this))
  63. else {
  64. promise.resolve(this)
  65. }
  66. }
  67. })
  68. return promise
  69. }
  70. }
  71. else {
  72. delete this.then
  73. }
  74. }
  75. get createdAt(){
  76. return this._id ? new Date(this._id.getTimestamp()) : null
  77. }
  78. get collection(){
  79. return db.collection(this._class)
  80. }
  81. async save(noSync=false){
  82. if (this.validate && !(await this.validate())){
  83. throw new SyntaxError(`validation error on entity ${this._id} of class ${this.constructor.name} (${this.name || this.key}) save`)
  84. }
  85. if (this.empty) return this;
  86. const syncRelations = async () => {
  87. if (noSync) return
  88. if (!(this && this.__proto__ && this.__proto__.constructor && this.__proto__.constructor.relations)) return
  89. async function getValueByField(field, savable) {
  90. let path = field.split('.');
  91. await savable//.catch(e => console.log('GET VALUE BY FIELD ERROR'));
  92. let result = savable;
  93. let prev;
  94. let lastKey = path.pop()
  95. while (prev = result, result = result[path.shift()] && path.length);
  96. return {value: prev[lastKey], obj: prev, lastKey};
  97. }
  98. for (const relation in this.__proto__.constructor.relations){
  99. let backRef = this.__proto__.constructor.relations[relation]
  100. if (Array.isArray(backRef)) backRef = backRef[0]
  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){ //check for removed Refs
  106. const removedRefs = valueAsArray ?
  107. loadRelationAsArray.filter(ref => !Savable.existsInArray(valueAsArray, ref)) :
  108. loadRelationAsArray
  109. for (const ref of removedRefs){
  110. try { await ref } catch (e) {console.log('SYNC RELATIONS REMOVE ERROR') }
  111. if (ref instanceof Savable)
  112. await ref.removeRelation(this, relation)
  113. }
  114. }
  115. if (valueAsArray){ //check for added refs
  116. for (const foreignSavable of valueAsArray) {
  117. try { await foreignSavable } catch (e) {console.log('SYNC RELATIONS ADD ERROR') }
  118. let foreignLoadRelationsAsArray = Savable.arrize(foreignSavable._loadRelations[backRef])
  119. if (foreignSavable && !Savable.existsInArray(foreignLoadRelationsAsArray, this)){
  120. await foreignSavable.setRelation(this, relation)
  121. }
  122. }
  123. }
  124. }
  125. }
  126. async function recursiveSlicer(obj){
  127. let result = obj instanceof Array ? [] : {}
  128. for (const key in obj){
  129. if (obj[key] && typeof obj[key] === 'object'){
  130. if (obj[key] instanceof Savable){
  131. if (!(obj[key]._id)){
  132. await obj[key].save().catch(err => console.log('ERR', err))
  133. }
  134. result[key] = obj[key].shortData()
  135. }
  136. else {
  137. result[key] = await recursiveSlicer(obj[key])
  138. }
  139. }
  140. else {
  141. result[key] = obj[key]
  142. }
  143. }
  144. return result;
  145. }
  146. const {_id, _empty, _ref, _loadRelations, then, ...toSave} = await recursiveSlicer(this)
  147. //TODO: UPSERT
  148. if (!this._id){ //first time
  149. const { insertedId } = await this.collection.insertOne(toSave)
  150. this._id = insertedId
  151. }
  152. else { //update
  153. await this.collection.updateOne({_id: this._id}, {$set: toSave}).catch(err => console.log('UPDATE ERR', err))
  154. }
  155. await syncRelations()
  156. this.backupRelations()
  157. return this
  158. }
  159. // method to get ref snapshot (empty object with some data). gives optimizations in related objects
  160. // place for permission, owner, probably short relations
  161. shortData(){
  162. const {_id, _class} = this
  163. return { _id, _class }
  164. }
  165. async setRelation(ref, refRelationName){
  166. await this
  167. const ourRelation = ref.__proto__.constructor.relations[refRelationName]
  168. const ourArray = ourRelation instanceof Array
  169. const ourRelationName = ourArray ? ourRelation[0] : ourRelation
  170. let shortQuery = {[ourRelationName]: ref.shortData()}
  171. let query;
  172. if (ourArray || this[ourRelationName] instanceof Array){
  173. this[ourRelationName] = this[ourRelationName] || []
  174. this[ourRelationName] = this[ourRelationName] instanceof Array ? this[ourRelationName] : [this[ourRelationName]]
  175. if (!Savable.existsInArray(this[ourRelationName], ref)) {
  176. this[ourRelationName].push(ref)
  177. if (this._id && this._loadRelations[ourRelationName] instanceof Array){
  178. this._loadRelations[ourRelationName].push(ref)
  179. }
  180. }
  181. query = {$addToSet: shortQuery}
  182. }
  183. else {
  184. this[ourRelationName] = ref
  185. this._id && (this._loadRelations[ourRelationName] = ref)
  186. query = {$set: shortQuery}
  187. }
  188. console.log('SET RELATION:', query)
  189. if (this._id){
  190. console.log('SET RELATION:', query)
  191. await this.collection.updateOne({_id: this._id}, query).catch(err => console.log('UPDATE ERR', err))
  192. }
  193. }
  194. async removeRelation(ref, refRelationName){ //i. e. this = child, ref = parent object, refRelationName = children in parent
  195. await this
  196. const ourRelation = ref.__proto__.constructor.relations[refRelationName]
  197. const ourArray = ourRelation instanceof Array
  198. const ourRelationName = ourArray ? ourRelation[0] : ourRelation
  199. if (this._id){
  200. const query = ourArray ? {$pull: {[ourRelationName]: ref.shortData()}}
  201. : {$set: {[ourRelationName]: null}}
  202. console.log('REMOVE RELATION:', query)
  203. await this.collection.updateOne({_id: this._id}, query).catch(err => console.log('UPDATE ERR', err))
  204. }
  205. (this[ourRelationName] instanceof Array) ? this._loadRelations[ourRelationName] = this[ourRelationName] = this[ourRelationName].filter(ourRef => !ourRef.equals(ref))
  206. : this[ourRelationName] = null;
  207. }
  208. async delete(noRefs=false){
  209. if (!noRefs) for (const relation in this.__proto__.constructor.relations){
  210. const backRef = this.__proto__.constructor.relations[relation]
  211. const loadRelation = this._loadRelations && this._loadRelations[relation]
  212. const loadRelationAsArray = loadRelation instanceof Savable ? [loadRelation] : loadRelation
  213. if (loadRelationAsArray){
  214. for (const ref of loadRelationAsArray){
  215. try {
  216. await ref
  217. }
  218. catch (e) {console.log('DELETE SYNC RELATIONS ERROR') }
  219. if (ref instanceof Savable)
  220. await ref.removeRelation(this, relation)
  221. }
  222. }
  223. }
  224. const id = this._id
  225. const col = this._class && this.collection
  226. for (let key in this)
  227. delete this[key]
  228. delete this.__proto__
  229. if (col)
  230. return await col.deleteOne({_id: id})
  231. }
  232. static arrize(value){
  233. if (Array.isArray(value)) return value
  234. if (value) return [value]
  235. return []
  236. }
  237. static equals(obj1, obj2){
  238. if (!obj1 || !obj2) return false
  239. if(!obj1._id) return obj1 === obj2
  240. if(!obj2._id) return obj1 === obj2
  241. return obj1._id.toString() === obj2._id.toString()
  242. }
  243. equals(obj){
  244. return Savable.equals(this, obj)
  245. }
  246. static existsInArray(arr, obj){
  247. if (!Array.isArray(arr)) return false
  248. let filtered = arr.filter(item => Savable.equals(item, obj))
  249. return filtered.length
  250. }
  251. static isSavable(obj){
  252. return obj && obj._id && obj._class
  253. }
  254. static newSavable(obj, ref, empty=true){
  255. let className = obj._class || "Savable"
  256. className = Savable.classes[className] ? className : "Savable"
  257. if (obj.__proto__.constructor === Savable.classes[className]){
  258. return obj
  259. }
  260. return new Savable.classes[className](obj, ref, empty)
  261. }
  262. static addClass(_class){ //explicit method to add class to Savable registry for instantiate right class later
  263. (typeof _class == 'function') && (Savable.classes[_class.name] = _class)
  264. }
  265. static get m(){
  266. return Savable._m = (Savable._m || (new Proxy({}, {
  267. get(obj, _class){
  268. if (_class in obj){
  269. return obj[_class]
  270. }
  271. const applyCursorCalls = (cursor, calls) =>{
  272. if (!calls) return cursor;
  273. for (let [method, params] of Object.entries(calls)){
  274. if (typeof cursor[method] !== "function"){
  275. throw new SyntaxError(`Wrong cursor method ${method}`)
  276. }
  277. cursor = cursor[method](...params)
  278. }
  279. return cursor;
  280. }
  281. return obj[_class] = {
  282. * find(query, cursorCalls={}){
  283. //console.log(query)
  284. let cursor = applyCursorCalls(db.collection(_class).find(query), cursorCalls)
  285. let cursorGen = asynchronize({s: cursor.stream(),
  286. chunkEventName: 'data',
  287. endEventName: 'close',
  288. errEventName: 'error',
  289. countMethodName: 'count'})
  290. for (const pObj of cursorGen()){
  291. yield new Promise((ok, fail) =>
  292. pObj.then(obj => (/*console.log(obj),*/ok(Savable.newSavable(obj, null, false))),
  293. err => fail(err)))
  294. }
  295. },
  296. async count(query, cursorCalls={}){
  297. let cursor = applyCursorCalls(db.collection(_class).find(query), cursorCalls)
  298. return await cursor.count(true)
  299. },
  300. async findOne(query){
  301. let result = await db.collection(_class).findOne(query)
  302. if (result)
  303. return Savable.newSavable(result, null, false)
  304. return result
  305. }
  306. }
  307. },
  308. set(obj, propName, value){
  309. }
  310. })))
  311. }
  312. static get relations(){
  313. //empty default relations, acceptable: {field: foreignField}, where:
  314. //field and foreign field can be Savable, Array or Set
  315. //both fields can be specified as "field", "field.subfield"
  316. //or field: {subfield: foreignField} //TODO later if needed
  317. //TODO: move it into object instead of class to give more flexibility, for example
  318. //if person has children, it can have backRef father or mother depending on sex:
  319. //return {
  320. // children: this.sex === 'male' ? 'father': 'mother'
  321. //}
  322. //
  323. //return {
  324. // parent: ["children"],
  325. // notebooks: "owner"
  326. //}
  327. return {}
  328. }
  329. }
  330. Savable.classes = {Savable}
  331. /**
  332. * sliceSavable - slice (limit) Savables for some permission
  333. * Array userACL - array of objectIDs, words or savable refs - current user, group objectid, or `tags` or `role` (ACL)
  334. */
  335. function sliceSavable(userACL){
  336. userACL = userACL.map(tag => tag.toString())
  337. //console.log(userACL)
  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){
  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)
  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
  474. }
  475. return {Savable, 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. }