index.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. saveRelations(){
  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.saveRelations()
  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(noRefs=false, 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. let setBackRef = async (backRef, foreignSavable) => {
  94. const {value: backRefValue,
  95. obj: backRefObj,
  96. lastKey: backRefKey} = await getValueByField(backRef, foreignSavable)
  97. if (backRefValue instanceof Array){
  98. if (!backRefValue.includes(this)){
  99. backRefValue.push(this)
  100. }
  101. }
  102. else {
  103. backRefObj[backRefKey] = this
  104. }
  105. noRefs || await foreignSavable.save(true)
  106. }
  107. for (const relation in this.__proto__.constructor.relations){
  108. const backRef = this.__proto__.constructor.relations[relation]
  109. const loadRelation = this._loadRelations[relation]
  110. const loadRelationAsArray = loadRelation instanceof Savable ? [loadRelation] : loadRelation
  111. let {value, obj, lastKey: key} = await getValueByField(relation, this)
  112. const valueAsArray = value instanceof Savable ? [value] : value
  113. if (loadRelationAsArray){
  114. const removedRefs = valueAsArray ? loadRelationAsArray.filter(ref => !valueAsArray.includes(ref)) : loadRelationAsArray
  115. for (const ref of removedRefs){
  116. try {
  117. await ref
  118. }
  119. catch (e) {console.log('SYNC RELATIONS ERROR') }
  120. if (ref[backRef] instanceof Array){
  121. ref[backRef] = ref[backRef].filter(br => br._id !== this._id)
  122. }
  123. else {
  124. ref[backRef] = null
  125. }
  126. noRefs || await ref.save(true)
  127. }
  128. }
  129. if (valueAsArray){
  130. for (const foreignSavable of valueAsArray){
  131. await setBackRef(backRef, foreignSavable)
  132. }
  133. }
  134. }
  135. }
  136. async function recursiveSlicer(obj){
  137. let result = obj instanceof Array ? [] : {}
  138. for (const key in obj){
  139. if (obj[key] && typeof obj[key] === 'object'){
  140. if (obj[key] instanceof Savable){
  141. if (!(obj[key]._id)){
  142. await obj[key].save().catch(err => console.log('ERR', err))
  143. }
  144. result[key] = {_id: obj[key]._id, _class: obj[key]._class}
  145. }
  146. else {
  147. result[key] = await recursiveSlicer(obj[key])
  148. }
  149. }
  150. else {
  151. result[key] = obj[key]
  152. }
  153. }
  154. return result;
  155. }
  156. const {_id, _empty, _ref, _loadRelations, then, ...toSave} = await recursiveSlicer(this)
  157. //TODO: UPSERT
  158. if (!this._id){ //first time
  159. const { insertedId } = await this.collection.insertOne(toSave)
  160. this._id = insertedId
  161. }
  162. else { //update
  163. await this.collection.updateOne({_id: this._id}, {$set: toSave}).catch(err => console.log('UPDATE ERR', err))
  164. }
  165. await syncRelations()
  166. this.saveRelations()
  167. return this
  168. }
  169. async delete(noRefs=false){
  170. if (!noRefs) for (const relation in this.__proto__.constructor.relations){
  171. const backRef = this.__proto__.constructor.relations[relation]
  172. const loadRelation = this._loadRelations && this._loadRelations[relation]
  173. const loadRelationAsArray = loadRelation instanceof Savable ? [loadRelation] : loadRelation
  174. if (loadRelationAsArray){
  175. for (const ref of loadRelationAsArray){
  176. try {
  177. await ref
  178. }
  179. catch (e) {console.log('DELETE SYNC RELATIONS ERROR') }
  180. if (ref[backRef] instanceof Array){
  181. ref[backRef] = ref[backRef].filter(br => br._id !== this._id)
  182. }
  183. else {
  184. ref[backRef] = null
  185. }
  186. await ref.save(true, true)
  187. }
  188. }
  189. }
  190. const id = this._id
  191. const col = this._class && this.collection
  192. for (let key in this)
  193. delete this[key]
  194. delete this.__proto__
  195. if (col)
  196. return await col.deleteOne({_id: id})
  197. }
  198. static isSavable(obj){
  199. return obj && obj._id && obj._class
  200. }
  201. static newSavable(obj, ref, empty=true){
  202. let className = obj._class || "Savable"
  203. className = Savable.classes[className] ? className : "Savable"
  204. if (obj.__proto__.constructor === Savable.classes[className]){
  205. return obj
  206. }
  207. return new Savable.classes[className](obj, ref, empty)
  208. }
  209. static addClass(_class){ //explicit method to add class to Savable registry for instantiate right class later
  210. (typeof _class == 'function') && (Savable.classes[_class.name] = _class)
  211. }
  212. static get m(){
  213. return new Proxy({}, {
  214. get(obj, _class){
  215. if (_class in obj){
  216. return obj[_class]
  217. }
  218. return obj[_class] = {
  219. * find(query, projection, cursorCalls={}){
  220. let cursor = db.collection(_class).find(query, projection)
  221. for (let [method, params] of Object.entries(cursorCalls)){
  222. if (typeof cursor[method] !== "function"){
  223. throw new SyntaxError(`Wrong cursor method ${method}`)
  224. }
  225. cursor = cursor[method](...params)
  226. }
  227. let cursorGen = asynchronize({s: cursor.stream(),
  228. chunkEventName: 'data',
  229. endEventName: 'close',
  230. errEventName: 'error',
  231. countMethodName: 'count'})
  232. for (const pObj of cursorGen()){
  233. yield new Promise((ok, fail) =>
  234. pObj.then(obj => (/*console.log(obj),*/ok(Savable.newSavable(obj, null, false))),
  235. err => fail(err)))
  236. }
  237. },
  238. async findOne(query, projection){
  239. let result = await db.collection(_class).findOne(query, projection)
  240. if (result)
  241. return Savable.newSavable(result, null, false)
  242. return result
  243. }
  244. }
  245. },
  246. set(obj, propName, value){
  247. }
  248. })
  249. }
  250. static get relations(){
  251. //empty default relations, acceptable: {field: foreignField}, where:
  252. //field and foreign field can be Savable, Array or Set
  253. //both fields can be specified as "field", "field.subfield"
  254. //or field: {subfield: foreignField} //TODO later if needed
  255. //TODO: move it into object instead of class to give more flexibility, for example
  256. //if person has children, it can have backRef father or mother depending on sex:
  257. //return {
  258. // children: this.sex === 'male' ? 'father': 'mother'
  259. //}
  260. return {}
  261. }
  262. }
  263. Savable.classes = {Savable}
  264. /**
  265. * sliceSavable - slice (limit) Savables for some permission
  266. * Array userACL - array of objectIDs, words or savable refs - current user, group objectid, or `tags` or `role` (ACL)
  267. */
  268. function sliceSavable(userACL){
  269. userACL = userACL.map(tag => tag.toString())
  270. //console.log(userACL)
  271. class SlicedSavable extends Savable {
  272. constructor(...params){
  273. super (...params)
  274. if (!this._empty){
  275. this.___permissionsPrepare()
  276. }
  277. }
  278. ___permissionsPrepare(){
  279. if (this._empty) return
  280. if (!this.___permissions) this.___permissions = {}
  281. for (let [perm, acl] of Object.entries(this.__proto__.constructor.defaultPermissions)){
  282. if (!this.___permissions[perm]){
  283. this.___permissions[perm] = [...acl]
  284. }
  285. }
  286. }
  287. ___permissionCan(permission, permissions=this.___permissions, obj=this){
  288. const acl = (permissions &&
  289. permissions[permission] ||
  290. this.__proto__.constructor.defaultPermissions[permission]).map(tag => tag.toString())
  291. if (acl.includes('owner') && obj.___owner && userACL.includes(obj.___owner.toString())){
  292. return true
  293. }
  294. for (let uTag of userACL){
  295. if (acl.includes(uTag)){
  296. return true
  297. }
  298. }
  299. return false
  300. }
  301. populate(obj){ //place to check read permission
  302. //console.log(obj)
  303. if (!this.___permissionCan('read', obj.___permissions, obj)){
  304. throw new ReferenceError(`No Access To Entity ${this._id} of class ${this._class}`)
  305. }
  306. super.populate(obj)
  307. }
  308. async save(noRefs=false, noSync=false){
  309. if (!this._id && !this.___permissionCan('create'))
  310. throw new ReferenceError(`Permissison denied Create Entity of class ${this._class}`)
  311. if (this._id && !this.___permissionCan('write') && !noRefs) //give ability to change backrefs for not permitted records
  312. throw new ReferenceError(`Permissison denied Save Entity ${this._id} of class ${this._class}`)
  313. if (!this._id){
  314. this.___owner = userACL[0] //TODO fix objectid troubles
  315. //console.log(typeof this.___owner, this.___owner)
  316. }
  317. return await super.save(noRefs, noSync)
  318. }
  319. async delete(noRefs=false){
  320. if (!this.___permissionCan('delete'))
  321. throw new ReferenceError(`Permissison denied Delete Entity ${this._id} of class ${this._class}`)
  322. return await super.delete(noRefs)
  323. }
  324. static ___permissionQuery(permission){
  325. //const withObjectIDs = userACL.map((a,id) => (id = new ObjectID(a)) && id.toString() === a ? id : a)
  326. const withObjectIDs = userACL
  327. return {
  328. $or: [
  329. {[`___permissions.${permission}`]: {$in: withObjectIDs}},
  330. {$and: [{[`___permissions.${permission}`]: "owner"},
  331. {___owner: userACL[0]}]}]
  332. }
  333. }
  334. static get m() {
  335. return new Proxy({}, {
  336. get(obj, _class){
  337. if (_class in obj){
  338. return obj[_class]
  339. }
  340. return obj[_class] = {
  341. * find(query, projection, cursorCalls={}){
  342. const originalClass = Savable.classes[_class]
  343. Savable.addClass(SlicedSavable.classes[_class])
  344. let permittedQuery = {$and: [SlicedSavable.___permissionQuery('read') ,query]}
  345. //console.log(JSON.stringify(permittedQuery, null, 4))
  346. let iter = Savable.m[_class].find(permittedQuery, projection, cursorCalls)
  347. Savable.addClass(originalClass)
  348. yield* iter;
  349. },
  350. async findOne(query, projection){
  351. const originalClass = Savable.classes[_class]
  352. Savable.addClass(SlicedSavable.classes[_class])
  353. const permittedQuery = {$and: [SlicedSavable.___permissionQuery('read') ,query]}
  354. const p = Savable.m[_class].findOne(permittedQuery, projection)
  355. Savable.addClass(originalClass)
  356. return await p;
  357. }
  358. }
  359. },
  360. set(obj, propName, value){
  361. }
  362. })
  363. }
  364. static get defaultPermissions(){
  365. return {
  366. //savable refs, objectid's, words like 'tags' or 'roles'
  367. read: ['owner', 'user'],
  368. write: ['owner', 'admin'],
  369. create: ['user'],
  370. delete: ['admin'],
  371. /*permission
  372. * TODO: permissions for read and write permissions
  373. *
  374. */
  375. }
  376. }
  377. }
  378. return SlicedSavable
  379. }
  380. return {Savable, sliceSavable}
  381. }
  382. async function connect(dbName, dsn="mongodb://localhost:27017/"){
  383. if (!dbName)
  384. throw new ReferenceError(`db name does not provided`)
  385. const mongoClient = new MongoClient(dsn, { useNewUrlParser: true });
  386. const client = await mongoClient.connect()
  387. const db = client.db(dbName)
  388. const Savable = mm(db).Savable
  389. const slice = mm(db).sliceSavable
  390. return {
  391. Savable,
  392. slice,
  393. }
  394. }
  395. module.exports = {
  396. mm,
  397. connect
  398. }