index.js 21 KB

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