Browse Source

await works

Ivan Asmer 6 years ago
parent
commit
e2c270c4a3
4 changed files with 263 additions and 0 deletions
  1. 60 0
      index.js
  2. 98 0
      mm.js
  3. 81 0
      package-lock.json
  4. 24 0
      package.json

+ 60 - 0
index.js

@@ -0,0 +1,60 @@
+const MongoClient = require("mongodb").MongoClient;
+const mm          = require('./mm.js')
+const delay       = ms => new Promise(r => setTimeout(r.bind(ms), ms))
+ 
+;(async () => {
+    const mongoClient = new MongoClient("mongodb://localhost:27017/", { useNewUrlParser: true });
+    const client      = await mongoClient.connect()
+    const db          = client.db('mm')
+    const Savable     = mm(db)
+
+    //while(true){
+        //await (new Savable({timestamp: (new Date).getTime(), r: Math.random()})).save()
+        //let person = new Savable({
+            //name: 'Mykola',
+            //surname: 'Silniy',
+            //phones: ['105', '1'],
+            //children: [
+                //new Savable({
+                    //name: 'Marina',
+                    //surname: 'Silnaya',
+                    //phones: ['105', '1000503']
+                //}),
+                //new Savable({
+                    //name: 'Andrey',
+                    //surname: 'Silniy',
+                    //phones: ['103', '1000502']
+                //}),
+                //new Savable({
+                    //name: 'Fedor',
+                    //surname: 'Ivanova',
+                    //phones: ['102', '1000504'],
+                    //notebook: new Savable({
+                        //brand: 'dubovo'
+                    //})
+                //})
+            //]
+        //})
+
+        //await person.save()
+        //console.log(person)
+
+        //await delay(3000)
+    //}
+
+    let person = new Savable()
+    person._id = '5c79f5a952dd4e30b3e65a37';
+    console.log(person)
+    //let obj = {
+        //then(cb){
+            //process.nextTick(() => cb(obj))
+        //}
+    //}
+    //console.log(await obj)
+    console.log('empty await', await person)//.then(p => console.log(p))
+    console.log('sub await', (await person.children[0]))//.then(p => console.log(p))
+
+
+
+    client.close();
+})()

+ 98 - 0
mm.js

@@ -0,0 +1,98 @@
+const ObjectID  = require('mongodb').ObjectID
+
+module.exports = db => {
+    class Savable {
+        constructor(obj){
+            console.log('CONSTRUCTOR')
+            this._id    = null
+            this._class = this.__proto__.constructor.name
+            this._empty = true
+
+            Savable.classes = Savable.classes || []
+            Savable.classes.push(this.__proto__.constructor)
+
+            this.populate(obj)
+        }
+
+        populate(obj){
+            if (obj){
+                for (const key in obj) this[key] = obj[key]
+                this._empty = false
+            }
+        }
+
+        get _empty(){
+            return !!this.then
+        }
+
+        set _empty(value){
+            if (value){
+                this.then = (cb, err) => {
+                    if (!this._empty){
+                        cb(this)
+                        return this
+                    }
+                    delete this.then
+                    if (!this._id) err(new ReferenceError('Id is empty'))
+                    if (!this._class) err(new ReferenceError('Class is empty'))
+
+                    this.collection.findOne({_id: ObjectID(this._id)}).then( data => {
+                        if (!data){
+                            err(new ReferenceError('Document Not Found'))
+                        }
+                        this.populate(data)
+                        cb(this)
+                    })
+                    return this
+                }
+            }
+            else {
+                delete this.then
+            }
+        }
+
+        get collection(){
+            return db.collection(this._class)
+        }
+
+        async save(){
+            if (this.empty) return;
+
+            async function recursiveSlicer(obj){
+                let result = obj instanceof Array ? [] : {}
+                for (const key in obj){
+                    if (obj[key] && typeof obj[key] === 'object'){
+                        if (obj[key] instanceof Savable){
+                            if (!(obj[key]._id)){
+                                await obj[key].save()
+                            }
+                            result[key] = {_id: obj[key]._id, _class: obj[key]._class}
+                        }
+                        else {
+                            console.log('recursion', obj, key)
+                            result[key] = await recursiveSlicer(obj[key])
+                        }
+                    }
+                    else {
+                        result[key] = obj[key]
+                    }
+                }
+                return result;
+            }
+
+            const toSave = await recursiveSlicer(this)
+            console.log(toSave)
+
+            if (!this._id){ //first time
+                delete toSave._id
+                delete toSave._empty
+                const { insertedId } = await this.collection.insertOne(toSave)
+                this._id = insertedId
+            }
+            else { //updateOne
+                this.collection.updateOne(toSave, {_id: this._id})
+            }
+        }
+    }
+    return Savable
+}

+ 81 - 0
package-lock.json

@@ -0,0 +1,81 @@
+{
+  "name": "mm",
+  "version": "1.0.0",
+  "lockfileVersion": 1,
+  "requires": true,
+  "dependencies": {
+    "bson": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/bson/-/bson-1.1.0.tgz",
+      "integrity": "sha512-9Aeai9TacfNtWXOYarkFJRW2CWo+dRon+fuLZYJmvLV3+MiUp0bEI6IAZfXEIg7/Pl/7IWlLaDnhzTsD81etQA=="
+    },
+    "memory-pager": {
+      "version": "1.5.0",
+      "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz",
+      "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==",
+      "optional": true
+    },
+    "mongodb": {
+      "version": "3.1.13",
+      "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.1.13.tgz",
+      "integrity": "sha512-sz2dhvBZQWf3LRNDhbd30KHVzdjZx9IKC0L+kSZ/gzYquCF5zPOgGqRz6sSCqYZtKP2ekB4nfLxhGtzGHnIKxA==",
+      "requires": {
+        "mongodb-core": "3.1.11",
+        "safe-buffer": "^5.1.2"
+      }
+    },
+    "mongodb-core": {
+      "version": "3.1.11",
+      "resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-3.1.11.tgz",
+      "integrity": "sha512-rD2US2s5qk/ckbiiGFHeu+yKYDXdJ1G87F6CG3YdaZpzdOm5zpoAZd/EKbPmFO6cQZ+XVXBXBJ660sSI0gc6qg==",
+      "requires": {
+        "bson": "^1.1.0",
+        "require_optional": "^1.0.1",
+        "safe-buffer": "^5.1.2",
+        "saslprep": "^1.0.0"
+      }
+    },
+    "require_optional": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz",
+      "integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==",
+      "requires": {
+        "resolve-from": "^2.0.0",
+        "semver": "^5.1.0"
+      }
+    },
+    "resolve-from": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz",
+      "integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c="
+    },
+    "safe-buffer": {
+      "version": "5.1.2",
+      "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
+      "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
+    },
+    "saslprep": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.2.tgz",
+      "integrity": "sha512-4cDsYuAjXssUSjxHKRe4DTZC0agDwsCqcMqtJAQPzC74nJ7LfAJflAtC1Zed5hMzEQKj82d3tuzqdGNRsLJ4Gw==",
+      "optional": true,
+      "requires": {
+        "sparse-bitfield": "^3.0.3"
+      }
+    },
+    "semver": {
+      "version": "5.6.0",
+      "resolved": "https://registry.npmjs.org/semver/-/semver-5.6.0.tgz",
+      "integrity": "sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg=="
+    },
+    "sparse-bitfield": {
+      "version": "3.0.3",
+      "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz",
+      "integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=",
+      "optional": true,
+      "requires": {
+        "memory-pager": "^1.0.2"
+      }
+    }
+  }
+}

+ 24 - 0
package.json

@@ -0,0 +1,24 @@
+{
+  "name": "mm",
+  "version": "1.0.0",
+  "description": "",
+  "main": "index.js",
+  "scripts": {
+    "test": "echo \"Error: no test specified\" && exit 1"
+  },
+  "repository": {
+    "type": "git",
+    "url": "git@gitlab.a-level.com.ua:gitgod/mm.git"
+  },
+  "keywords": [
+    "node",
+    "mongo",
+    "memory",
+    "orm"
+  ],
+  "author": "Ivan Grynkin",
+  "license": "ISC",
+  "dependencies": {
+    "mongodb": "^3.1.13"
+  }
+}