From d2ea9b600b332e634bb553ea8ac1a3665f8fbae7 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 07:28:14 +0800 Subject: [PATCH 01/18] replace diyStore with @jsonql/store --- packages/@jsonql/security/package.json | 1 + .../security/src/cache/csrf-methods.js | 6 +- .../@jsonql/security/src/cache/diy-cache.js | 63 ------------------- .../@jsonql/security/src/cache/get-cache.js | 6 +- 4 files changed, 7 insertions(+), 69 deletions(-) delete mode 100644 packages/@jsonql/security/src/cache/diy-cache.js diff --git a/packages/@jsonql/security/package.json b/packages/@jsonql/security/package.json index d9461955..cb30230b 100644 --- a/packages/@jsonql/security/package.json +++ b/packages/@jsonql/security/package.json @@ -38,6 +38,7 @@ "author": "Joel Chu ", "license": "ISC", "dependencies": { + "@jsonql/store": "^0.9.0", "colors": "^1.4.0", "fs-extra": "^9.0.0", "jsonql-constants": "^2.0.14", diff --git a/packages/@jsonql/security/src/cache/csrf-methods.js b/packages/@jsonql/security/src/cache/csrf-methods.js index b6ad076a..53c61841 100644 --- a/packages/@jsonql/security/src/cache/csrf-methods.js +++ b/packages/@jsonql/security/src/cache/csrf-methods.js @@ -16,7 +16,7 @@ function getToken(store) { let token = nanoid() // test if the token exist - if (store.$has(token)) { + if (store.has(token)) { // call itself again until find a key not in store return getToken(store) } @@ -31,7 +31,7 @@ function getToken(store) { function createCSRFToken(store) { let token = getToken(store) // not setting the TTL at the moment, but we should in the future - if (store.$set(token, Date.now())) { + if (store.set(token, Date.now())) { return token } throw new JsonqlError('createCSRFToken', STORE_FAIL_ERR) @@ -44,7 +44,7 @@ function createCSRFToken(store) { * @return {boolean} */ function isCSRFTokenExist(store, token) { - return store.$has(token) + return store.has(token) } diff --git a/packages/@jsonql/security/src/cache/diy-cache.js b/packages/@jsonql/security/src/cache/diy-cache.js deleted file mode 100644 index 0d37b3ec..00000000 --- a/packages/@jsonql/security/src/cache/diy-cache.js +++ /dev/null @@ -1,63 +0,0 @@ -// just fucking around with the cache object -// NodeCache is a piece of shit - - -class DiyCache { - - constructor(opts = {}) { - const { log } = opts - if (typeof log === 'function') { - this.$log = log - } - - this.$store = new Map() - } - - // placeeholder - $log() { - - } - - // alias - $has(key) { - return this.$store.has(key) || false - } - - // note this actually return the value itself - $set(key, value) { - this.$store.set(key, value) - return this.$has(key) - } - - // get it and make sure it return boolen false when nothing - $get(key) { - return this.$store.get(key) || false - } - - // alias to delete - $remove(key) { - return this.$store.delete(key) - } - - // return the key value then remove it - $take(key) { - if (this.has(key)) { - const value = this.$store.get(key) - this.remove(key) - return value - } - return false - } - - // alias to entries return interable object - $all() { - return this.$store.entries() - } - - $size() { - return this.$store.size - } - -} - -module.exports = { DiyCache } diff --git a/packages/@jsonql/security/src/cache/get-cache.js b/packages/@jsonql/security/src/cache/get-cache.js index d83cd430..5f923e60 100644 --- a/packages/@jsonql/security/src/cache/get-cache.js +++ b/packages/@jsonql/security/src/cache/get-cache.js @@ -23,7 +23,7 @@ maxKeys: (default: -1) specifies a maximum amount of keys that can be stored in // const NodeCache = require('node-cache') // need to rethink should we do it like this // global.jsonqlLocalNodeCacheStore = {} -const { DiyCache } = require('./diy-cache') +const { JsonqlStore } = require('@jsonql/store') /** * We dont' use the global property like before anymore * Because that could be a security risk @@ -31,7 +31,7 @@ const { DiyCache } = require('./diy-cache') * @return {object} the nodeCache instance */ function getCache(opts = {}) { - return new DiyCache(opts) + return new JsonqlStore(opts) } /** @@ -39,7 +39,7 @@ function getCache(opts = {}) { * @param {*} store */ function isCacheObj(store) { - return store instanceof DiyCache + return store instanceof JsonqlStore } module.exports = { -- Gitee From 96e4a2128aea808166f1f82f61e379859ce3c856 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 07:29:21 +0800 Subject: [PATCH 02/18] test passed --- packages/@jsonql/security/tests/cache.test.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/@jsonql/security/tests/cache.test.js b/packages/@jsonql/security/tests/cache.test.js index b83dc757..6bc16a5c 100644 --- a/packages/@jsonql/security/tests/cache.test.js +++ b/packages/@jsonql/security/tests/cache.test.js @@ -38,17 +38,17 @@ test(`Test our own DiyCache`, t => { return `Hello yes, I got your: ${msg}` } - const result1 = store.$set(key, callme) + const result1 = store.set(key, callme) debug('take a look at what return', result1) - const fn1 = store.$get(key) + const fn1 = store.get(key) const msg1 = fn1('moron') t.truthy(msg1.indexOf('moron')) t.true(typeof fn1 === 'function') - const fn2 = store.$get(key) + const fn2 = store.get(key) const msg2 = fn2('indiot!') t.truthy(msg2.indexOf('indiot')) -- Gitee From 8489794c96325e7307898c8ff3c198897a56d7be Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 09:40:12 +0800 Subject: [PATCH 03/18] create several internal methods for the next development --- packages/@jsonql/store/package.json | 2 +- .../@jsonql/store/src/jsonql-store-class.js | 93 ++++++++++++++----- .../@jsonql/store/tests/event-off.test.js | 11 +++ 3 files changed, 84 insertions(+), 22 deletions(-) create mode 100644 packages/@jsonql/store/tests/event-off.test.js diff --git a/packages/@jsonql/store/package.json b/packages/@jsonql/store/package.json index 6fd4a27c..ccb82822 100644 --- a/packages/@jsonql/store/package.json +++ b/packages/@jsonql/store/package.json @@ -1,6 +1,6 @@ { "name": "@jsonql/store", - "version": "0.9.0", + "version": "0.9.1", "description": "A super simple in-memory key value store also provide a event hook for you to hook into the storage of your choice", "main": "dist/jsonql-store.cjs.js", "browser": "dist/jsonql-store.umd.js", diff --git a/packages/@jsonql/store/src/jsonql-store-class.js b/packages/@jsonql/store/src/jsonql-store-class.js index e18dccb5..de19d37d 100644 --- a/packages/@jsonql/store/src/jsonql-store-class.js +++ b/packages/@jsonql/store/src/jsonql-store-class.js @@ -21,10 +21,52 @@ export class JsonqlStore extends EventClass { * @param {*} opts */ constructor(opts = {}) { - super(opts) + super(opts) + // @0.9.1 add a switch to turn off the event + this.__eventOff = !!opts.eventOff this.$store = new Map() } + ////////////////////////////////// + // PRIVATE METHODS // + ////////////////////////////////// + + + /** + * Wrap all event emit here and can be turn off via the eventOff = true + * @param {*} evtName + * @param {array} payload expect an array but you need to diy it! + * @return {*} undefined means did nothing + */ + __emit(evtName, payload) { + if (this.__eventOff === false) { + return this.$trigger(evtName, payload) + } + } + + /** + * a wraper method to create the stored items + * @TODO add timestamp using a Set etc + * @param {*} value whatever you want to store + * @return {*} TBC + */ + __wrap(value) { + return value + } + + /** + * Unwrap our internal store and return the value + * @param {*} value + * @return {*} TBC + */ + __unwrap(value) { + return value + } + + ////////////////////////////////// + // PUBLIC METHODS // + ////////////////////////////////// + /** * Check key exist * @param {*} key @@ -32,7 +74,7 @@ export class JsonqlStore extends EventClass { */ has(key) { const result = this.$store.has(key) || false - this.$trigger(HAS_EVT, [key, result]) + this.__emit(HAS_EVT, [key, result]) return result } @@ -45,7 +87,7 @@ export class JsonqlStore extends EventClass { */ set(key, value) { this.$store.set(key, value) - this.$trigger(SET_EVT, [key, value]) + this.__emit(SET_EVT, [key, value]) return this.has(key) } @@ -57,7 +99,7 @@ export class JsonqlStore extends EventClass { */ get(key) { const result = this.$store.get(key) || false - this.$trigger(GET_EVT, [key, result]) + this.__emit(GET_EVT, [key, result]) return result } @@ -69,7 +111,7 @@ export class JsonqlStore extends EventClass { */ delete(key) { const result = this.$store.delete(key) - this.$trigger(DELETE_EVT, [key, result]) + this.__emit(DELETE_EVT, [key, result]) return result } @@ -82,36 +124,44 @@ export class JsonqlStore extends EventClass { take(key) { if (this.has(key)) { const value = this.$store.get(key) - this.$trigger(TAKE_EVT, [key, value]) + this.__emit(TAKE_EVT, [key, value]) // we call the native method because we don't want to trigger the delete event again this.$store.delete(key) return value } - this.$trigger(TAKE_EVT, [key]) + this.__emit(TAKE_EVT, [key]) return false } /** * alias to entries return interable object - * @param {boolean} arr return as array or not - * @return {array} + * @param {boolean} [arr=true] return as array or not + * @return {array} this is the default now */ - all(arr = false) { - const result = this.$store.entries() + all(arr = true) { + const result = this.offload() const returnResult = arr ? Array.from(result) : result - this.$trigger(ALL_EVT, [returnResult]) + this.__emit(ALL_EVT, [returnResult]) return returnResult } + /** + * Offloading the store return just the raw data + * @return {*} object + */ + offload() { + return this.$store.entries() + } + /** * Get the size (length) of the store * @return {number} */ size() { const result = this.$store.size - this.$trigger(SIZE_EVT, [result]) + this.__emit(SIZE_EVT, [result]) return result } @@ -130,7 +180,7 @@ export class JsonqlStore extends EventClass { */ clear() { this.$store.clear() - this.$trigger(CLEAR_EVT) + this.__emit(CLEAR_EVT) // @TODO should we clear out all the event listeners as well? } @@ -139,16 +189,17 @@ export class JsonqlStore extends EventClass { * @param {string} evtName * @param {function} callback * @param {*} context - * @return {*} + * @return {*} return undefined means it did nothing */ on(evtName, callback, context = null) { - const ok = !!AVAILABLE_EVTS.filter(e => e === evtName).length - if (ok) { - return this.$on(evtName, callback, context) - } - throw new Error(`${evtName} is not one of ours!`) + if (this.__eventOff === false) { + const ok = !!AVAILABLE_EVTS.filter(e => e === evtName).length + if (ok) { + return this.$on(evtName, callback, context) + } + throw new Error(`${evtName} is not one of ours!`) + } } - } diff --git a/packages/@jsonql/store/tests/event-off.test.js b/packages/@jsonql/store/tests/event-off.test.js new file mode 100644 index 00000000..1fe32401 --- /dev/null +++ b/packages/@jsonql/store/tests/event-off.test.js @@ -0,0 +1,11 @@ +const test = require('ava') +const { + JsonqlStore +} = require('../dist/jsonql-store.cjs') + +test(`Testing the event off`, t => { + + + + +}) \ No newline at end of file -- Gitee From 505c888f452523486e8d74671b17cb19a694367f Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 09:43:01 +0800 Subject: [PATCH 04/18] add script for testing the off --- packages/@jsonql/store/dist/jsonql-store.cjs.js | 2 +- packages/@jsonql/store/dist/jsonql-store.umd.js | 2 +- packages/@jsonql/store/package.json | 3 ++- packages/@jsonql/store/tests/event-off.test.js | 7 ++++++- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/@jsonql/store/dist/jsonql-store.cjs.js b/packages/@jsonql/store/dist/jsonql-store.cjs.js index 93e6dc5d..2d5c2164 100644 --- a/packages/@jsonql/store/dist/jsonql-store.cjs.js +++ b/packages/@jsonql/store/dist/jsonql-store.cjs.js @@ -1,2 +1,2 @@ -"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t="You are trying to register an event already been taken by other type:",e=["on","only","once","onlyOnce"],r=["on","only"];function o(t){return t instanceof RegExp}function n(t){return"string"==typeof t}function i(t){if(n(t))throw new Error("Wrong type, we want number!");return!isNaN(parseInt(t))}var s=new WeakMap,a=new WeakMap,u=function(){},l={$name:{configurable:!0},is:{configurable:!0}};u.prototype.logger=function(){},l.$name.get=function(){return"to1source-event"},l.is.get=function(){return this.$name},u.prototype.validateEvt=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.forEach((function(e){if(!n(e))throw t.logger("(validateEvt)",e),new Error("Event name must be string type! we got "+typeof e)})),!0},u.prototype.validate=function(t,e){if(this.validateEvt(t)&&"function"==typeof e)return!0;throw new Error("callback required to be function type! we got "+typeof e)},u.prototype.validateType=function(t){return this.validateEvt(t),!!e.filter((function(e){return t===e})).length},u.prototype.run=function(t,e,r){return this.logger("(run) callback:",t,"payload:",e,"context:",r),this.$done=Reflect.apply(t,r,this.toArray(e)),this.$done},u.prototype.hashFnToKey=function(t){return function(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}(t.toString())+""},Object.defineProperties(u.prototype,l);var h=["has","set","get","delete","take","all","size","clear"],p=function(t){function e(e){void 0===e&&(e={}),t.call(this,e),this.$store=new Map}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={length:{configurable:!0}};return e.prototype.has=function(t){var e=this.$store.has(t)||!1;return this.$trigger("has",[t,e]),e},e.prototype.set=function(t,e){return this.$store.set(t,e),this.$trigger("set",[t,e]),this.has(t)},e.prototype.get=function(t){var e=this.$store.get(t)||!1;return this.$trigger("get",[t,e]),e},e.prototype.delete=function(t){var e=this.$store.delete(t);return this.$trigger("delete",[t,e]),e},e.prototype.take=function(t){if(this.has(t)){var e=this.$store.get(t);return this.$trigger("take",[t,e]),this.$store.delete(t),e}return this.$trigger("take",[t]),!1},e.prototype.all=function(t){void 0===t&&(t=!1);var e=this.$store.entries(),r=t?Array.from(e):e;return this.$trigger("all",[r]),r},e.prototype.size=function(){var t=this.$store.size;return this.$trigger("size",[t]),t},r.length.get=function(){return this.size()},e.prototype.clear=function(){this.$store.clear(),this.$trigger("clear")},e.prototype.on=function(t,e,r){if(void 0===r&&(r=null),!!h.filter((function(e){return e===t})).length)return this.$on(t,e,r);throw new Error(t+" is not one of ours!")},Object.defineProperties(e.prototype,r),e}(function(e){function r(t){void 0===t&&(t={}),e.call(this,t)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var o={$done:{configurable:!0}};return r.prototype.$on=function(e,r,o){var n=this;void 0===o&&(o=null);this.validate(e,r);var i=this.takeFromStore(e);if(!1===i)return this.logger('($on) "'+e+'" is not in lazy store'),this.addToNormalStore(e,"on",r,o);this.logger("($on) "+e+" found in lazy store");var s=0;return i.forEach((function(i){var a=i[0],u=i[1],l=i[2];if(l&&"on"!==l)throw new Error(t+" "+l);n.logger("($on)",'call run "'+e+'"'),n.run(r,a,o||u),s+=n.addToNormalStore(e,"on",r,o||u)})),this.logger("($on) return size "+s),s},r.prototype.$once=function(e,r,o){void 0===o&&(o=null),this.validate(e,r);var n=this.takeFromStore(e);if(!1===n)return this.logger('($once) "'+e+'" is not in the lazy store'),this.addToNormalStore(e,"once",r,o);this.logger("($once)",n);var i=Array.from(n)[0],s=i[0],a=i[1],u=i[2];if(u&&"once"!==u)throw new Error(t+" "+u);this.logger("($once)",'call run "'+e+'"'),this.run(r,s,o||a),this.$off(e)},r.prototype.$only=function(e,r,o){var n=this;void 0===o&&(o=null),this.validate(e,r);var i=!1,s=this.takeFromStore(e);(this.normalStore.has(e)||(this.logger('($only) "'+e+'" add to normalStore'),i=this.addToNormalStore(e,"only",r,o)),!1!==s)&&(this.logger('($only) "'+e+'" found data in lazy store to execute'),Array.from(s).forEach((function(i){var s=i[0],a=i[1],u=i[2];if(u&&"only"!==u)throw new Error(t+" "+u);n.logger('($only) call run "'+e+'"'),n.run(r,s,o||a)})));return i},r.prototype.$onlyOnce=function(e,r,o){void 0===o&&(o=null),this.validate(e,r);var n=!1,i=this.takeFromStore(e);if(this.normalStore.has(e)||(this.logger('($onlyOnce) "'+e+'" add to normalStore'),n=this.addToNormalStore(e,"onlyOnce",r,o)),!1!==i){this.logger("($onlyOnce)",i);var s=Array.from(i)[0],a=s[0],u=s[1],l=s[2];if(l&&"onlyOnce"!==l)throw new Error(t+" "+l);this.logger('($onlyOnce) call run "'+e+'"'),this.run(r,a,o||u),this.$off(e)}return n},r.prototype.$max=function(t,e,r){if(void 0===r&&(r=null),this.validateEvt(t),i(e)&&e>0){if(!1!==this.$get(t,!0)){var o=this.searchMapEvt(t);if(o.length){var n=o[0][3],s=(this.checkMaxStore(t,e),this);return function(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];var i=s.getMaxStore(t),a=-1;if(i>0){var u=s.$call(t,n,r);if(Reflect.apply(u,s,e),-1===(a=s.checkMaxStore(t)))return s.$off(t),-1}return a}}}return this.logger("The "+t+" is not registered, can not execute non-existing event at the moment"),-1}throw new Error("Expect max to be an integer and greater than zero! But we got ["+typeof e+"]"+e+" instead")},r.prototype.$replace=function(t,e,r,o){if(void 0===r&&(r=null),void 0===o&&(o="on"),this.validateType(o)){this.$off(t);var n=this["$"+o];return this.logger("($replace)",t,e),Reflect.apply(n,this,[t,e,r])}throw new Error(o+" is not supported!")},r.prototype.$trigger=function(t,e,r,o){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===o&&(o=!1),this.validateEvt(t);var n=0,i=this.normalStore;if(this.logger("($trigger) normalStore",i),i.has(t)){if(this.logger('($trigger) "'+t+'" found'),this.$queue(t,e,r,o))return this.logger('($trigger) Currently suspended "'+t+'" added to queue, nothing executed. Exit now.'),!1;for(var s=Array.from(i.get(t)),a=s.length,u=!1,l=0;l0&&--r,!(r>0))return this.maxCountStore.delete(t),this.logger("remove "+t+" from maxStore"),-1;this.maxCountStore.set(t,r)}return r}throw new Error("Expect max to be an integer, but we got "+typeof e+" "+e)},e.prototype.searchMapEvt=function(t){var e=this.$get(t,!0).filter((function(t){var e,o=t[3];return e=o,!!r.filter((function(t){return e===t})).length}));return e.length?e:[]},e.prototype.takeFromStore=function(t,e){void 0===e&&(e="lazyStore");var r=this[e];if(r){if(this.logger("(takeFromStore)",e,r),r.has(t)){var o=r.get(t);return this.logger('(takeFromStore) has "'+t+'"',o),r.delete(t),o}return!1}throw new Error('"'+e+'" is not supported!')},e.prototype.findFromStore=function(t,e,r){return void 0===r&&(r=!1),!!e.has(t)&&Array.from(e.get(t)).map((function(t){return r?t:t[1]}))},e.prototype.removeFromStore=function(t,e){return!!e.has(t)&&(this.logger("($off)",t),e.delete(t),!0)},e.prototype.getStoreSet=function(t,e){var r;return t.has(e)?(this.logger('(addToStore) "'+e+'" existed'),r=t.get(e)):(this.logger('(addToStore) create new Set for "'+e+'"'),r=new Set),r},e.prototype.addToStore=function(t,e){for(var r=[],o=arguments.length-2;o-- >0;)r[o]=arguments[o+2];var n=this.getStoreSet(t,e);if(r.length>2)if(Array.isArray(r[0])){var i=r[2];this.checkTypeInLazyStore(e,i)||n.add(r)}else this.checkContentExist(r,n)||(this.logger("(addToStore) insert new",r),n.add(r));else n.add(r);return t.set(e,n),[t,n.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,o){if(void 0===o&&(o=null),this.logger('(addToNormalStore) try to add "'+e+'" --\x3e "'+t+'" to normal store'),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",'"'+e+'" --\x3e "'+t+'" can add to normal store');var n=this.hashFnToKey(r),i=[this.normalStore,t,n,r,o,e],s=Reflect.apply(this.addToStore,this,i),a=s[0],u=s[1];return this.normalStore=a,u}return!1},e.prototype.addToLazyStore=function(t,e,r,o){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===o&&(o=!1);var n=[this.lazyStore,t,this.toArray(e),r];o&&n.push(o);var i=Reflect.apply(this.addToStore,this,n),s=i[0],a=i[1];return this.lazyStore=s,this.logger("(addToLazyStore) size: "+a),a},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},o.normalStore.set=function(t){s.set(this,t)},o.normalStore.get=function(){return s.get(this)},o.lazyStore.set=function(t){a.set(this,t)},o.lazyStore.get=function(){return a.get(this)},Object.defineProperties(e.prototype,o),e}(function(t){function e(){t.call(this),this.__suspend_state__=null,this.__pattern__=null,this.queueStore=new Set}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$queues:{configurable:!0}};return e.prototype.$suspend=function(){this.logger("---\x3e SUSPEND ALL OPS <---"),this.__suspend__(!0)},e.prototype.$release=function(){this.logger("---\x3e RELEASE SUSPENDED QUEUE <---"),this.__suspend__(!1)},e.prototype.$suspendEvent=function(t){var e=function(t){switch(!0){case!0===o(t):return t;case!0===n(t):return new RegExp(t);default:return!1}}(t);if(o(e))return this.__pattern__=e,this.$suspend();throw new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof e+'" instead')},e.prototype.$queue=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];if(this.logger("($queue) get called"),!0===this.__suspend_state__){if(o(this.__pattern__)){var n=this.__pattern__.test(t);if(!n)return!1}this.logger("($queue) added to $queue",e),this.queueStore.add([t].concat(e))}return!!this.__suspend_state__},r.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},e.prototype.__suspend__=function(t){if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value! we got "+typeof t);var e=this.__suspend_state__;this.__suspend_state__=t,this.logger('($suspend) Change from "'+e+'" --\x3e "'+t+'"'),!0===e&&!1===t&&this.__release__()},e.prototype.__release__=function(){var t=this,e=this.queueStore.size,r=this.__pattern__;if(this.__pattern__=null,this.logger("(release) was called with "+e+(r?' for "'+r+'"':"")+" item"+(e>1?"s":"")),e>0){var o=Array.from(this.queueStore);this.queueStore.clear(),this.logger("(release queue)",o),o.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}return e},Object.defineProperties(e.prototype,r),e}(u))));exports.ALL_EVT="all",exports.AVAILABLE_EVTS=h,exports.CLEAR_EVT="clear",exports.DELETE_EVT="delete",exports.GET_EVT="get",exports.HAS_EVT="has",exports.JsonqlStore=p,exports.SET_EVT="set",exports.SIZE_EVT="size",exports.TAKE_EVT="take"; +"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t="You are trying to register an event already been taken by other type:",e=["on","only","once","onlyOnce"],r=["on","only"];function o(t){return t instanceof RegExp}function n(t){return"string"==typeof t}function i(t){if(n(t))throw new Error("Wrong type, we want number!");return!isNaN(parseInt(t))}var s=new WeakMap,a=new WeakMap,u=function(){},l={$name:{configurable:!0},is:{configurable:!0}};u.prototype.logger=function(){},l.$name.get=function(){return"to1source-event"},l.is.get=function(){return this.$name},u.prototype.validateEvt=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.forEach((function(e){if(!n(e))throw t.logger("(validateEvt)",e),new Error("Event name must be string type! we got "+typeof e)})),!0},u.prototype.validate=function(t,e){if(this.validateEvt(t)&&"function"==typeof e)return!0;throw new Error("callback required to be function type! we got "+typeof e)},u.prototype.validateType=function(t){return this.validateEvt(t),!!e.filter((function(e){return t===e})).length},u.prototype.run=function(t,e,r){return this.logger("(run) callback:",t,"payload:",e,"context:",r),this.$done=Reflect.apply(t,r,this.toArray(e)),this.$done},u.prototype.hashFnToKey=function(t){return function(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}(t.toString())+""},Object.defineProperties(u.prototype,l);var h=["has","set","get","delete","take","all","size","clear"],p=function(t){function e(e){void 0===e&&(e={}),t.call(this,e),this.__eventOff=!!e.eventOff,this.$store=new Map}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={length:{configurable:!0}};return e.prototype.__emit=function(t,e){if(!1===this.__eventOff)return this.$trigger(t,e)},e.prototype.__wrap=function(t){return t},e.prototype.__unwrap=function(t){return t},e.prototype.has=function(t){var e=this.$store.has(t)||!1;return this.__emit("has",[t,e]),e},e.prototype.set=function(t,e){return this.$store.set(t,e),this.__emit("set",[t,e]),this.has(t)},e.prototype.get=function(t){var e=this.$store.get(t)||!1;return this.__emit("get",[t,e]),e},e.prototype.delete=function(t){var e=this.$store.delete(t);return this.__emit("delete",[t,e]),e},e.prototype.take=function(t){if(this.has(t)){var e=this.$store.get(t);return this.__emit("take",[t,e]),this.$store.delete(t),e}return this.__emit("take",[t]),!1},e.prototype.all=function(t){void 0===t&&(t=!0);var e=this.offload(),r=t?Array.from(e):e;return this.__emit("all",[r]),r},e.prototype.offload=function(){return this.$store.entries()},e.prototype.size=function(){var t=this.$store.size;return this.__emit("size",[t]),t},r.length.get=function(){return this.size()},e.prototype.clear=function(){this.$store.clear(),this.__emit("clear")},e.prototype.on=function(t,e,r){if(void 0===r&&(r=null),!1===this.__eventOff){if(!!h.filter((function(e){return e===t})).length)return this.$on(t,e,r);throw new Error(t+" is not one of ours!")}},Object.defineProperties(e.prototype,r),e}(function(e){function r(t){void 0===t&&(t={}),e.call(this,t)}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var o={$done:{configurable:!0}};return r.prototype.$on=function(e,r,o){var n=this;void 0===o&&(o=null);this.validate(e,r);var i=this.takeFromStore(e);if(!1===i)return this.logger('($on) "'+e+'" is not in lazy store'),this.addToNormalStore(e,"on",r,o);this.logger("($on) "+e+" found in lazy store");var s=0;return i.forEach((function(i){var a=i[0],u=i[1],l=i[2];if(l&&"on"!==l)throw new Error(t+" "+l);n.logger("($on)",'call run "'+e+'"'),n.run(r,a,o||u),s+=n.addToNormalStore(e,"on",r,o||u)})),this.logger("($on) return size "+s),s},r.prototype.$once=function(e,r,o){void 0===o&&(o=null),this.validate(e,r);var n=this.takeFromStore(e);if(!1===n)return this.logger('($once) "'+e+'" is not in the lazy store'),this.addToNormalStore(e,"once",r,o);this.logger("($once)",n);var i=Array.from(n)[0],s=i[0],a=i[1],u=i[2];if(u&&"once"!==u)throw new Error(t+" "+u);this.logger("($once)",'call run "'+e+'"'),this.run(r,s,o||a),this.$off(e)},r.prototype.$only=function(e,r,o){var n=this;void 0===o&&(o=null),this.validate(e,r);var i=!1,s=this.takeFromStore(e);(this.normalStore.has(e)||(this.logger('($only) "'+e+'" add to normalStore'),i=this.addToNormalStore(e,"only",r,o)),!1!==s)&&(this.logger('($only) "'+e+'" found data in lazy store to execute'),Array.from(s).forEach((function(i){var s=i[0],a=i[1],u=i[2];if(u&&"only"!==u)throw new Error(t+" "+u);n.logger('($only) call run "'+e+'"'),n.run(r,s,o||a)})));return i},r.prototype.$onlyOnce=function(e,r,o){void 0===o&&(o=null),this.validate(e,r);var n=!1,i=this.takeFromStore(e);if(this.normalStore.has(e)||(this.logger('($onlyOnce) "'+e+'" add to normalStore'),n=this.addToNormalStore(e,"onlyOnce",r,o)),!1!==i){this.logger("($onlyOnce)",i);var s=Array.from(i)[0],a=s[0],u=s[1],l=s[2];if(l&&"onlyOnce"!==l)throw new Error(t+" "+l);this.logger('($onlyOnce) call run "'+e+'"'),this.run(r,a,o||u),this.$off(e)}return n},r.prototype.$max=function(t,e,r){if(void 0===r&&(r=null),this.validateEvt(t),i(e)&&e>0){if(!1!==this.$get(t,!0)){var o=this.searchMapEvt(t);if(o.length){var n=o[0][3],s=(this.checkMaxStore(t,e),this);return function(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];var i=s.getMaxStore(t),a=-1;if(i>0){var u=s.$call(t,n,r);if(Reflect.apply(u,s,e),-1===(a=s.checkMaxStore(t)))return s.$off(t),-1}return a}}}return this.logger("The "+t+" is not registered, can not execute non-existing event at the moment"),-1}throw new Error("Expect max to be an integer and greater than zero! But we got ["+typeof e+"]"+e+" instead")},r.prototype.$replace=function(t,e,r,o){if(void 0===r&&(r=null),void 0===o&&(o="on"),this.validateType(o)){this.$off(t);var n=this["$"+o];return this.logger("($replace)",t,e),Reflect.apply(n,this,[t,e,r])}throw new Error(o+" is not supported!")},r.prototype.$trigger=function(t,e,r,o){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===o&&(o=!1),this.validateEvt(t);var n=0,i=this.normalStore;if(this.logger("($trigger) normalStore",i),i.has(t)){if(this.logger('($trigger) "'+t+'" found'),this.$queue(t,e,r,o))return this.logger('($trigger) Currently suspended "'+t+'" added to queue, nothing executed. Exit now.'),!1;for(var s=Array.from(i.get(t)),a=s.length,u=!1,l=0;l0&&--r,!(r>0))return this.maxCountStore.delete(t),this.logger("remove "+t+" from maxStore"),-1;this.maxCountStore.set(t,r)}return r}throw new Error("Expect max to be an integer, but we got "+typeof e+" "+e)},e.prototype.searchMapEvt=function(t){var e=this.$get(t,!0).filter((function(t){var e,o=t[3];return e=o,!!r.filter((function(t){return e===t})).length}));return e.length?e:[]},e.prototype.takeFromStore=function(t,e){void 0===e&&(e="lazyStore");var r=this[e];if(r){if(this.logger("(takeFromStore)",e,r),r.has(t)){var o=r.get(t);return this.logger('(takeFromStore) has "'+t+'"',o),r.delete(t),o}return!1}throw new Error('"'+e+'" is not supported!')},e.prototype.findFromStore=function(t,e,r){return void 0===r&&(r=!1),!!e.has(t)&&Array.from(e.get(t)).map((function(t){return r?t:t[1]}))},e.prototype.removeFromStore=function(t,e){return!!e.has(t)&&(this.logger("($off)",t),e.delete(t),!0)},e.prototype.getStoreSet=function(t,e){var r;return t.has(e)?(this.logger('(addToStore) "'+e+'" existed'),r=t.get(e)):(this.logger('(addToStore) create new Set for "'+e+'"'),r=new Set),r},e.prototype.addToStore=function(t,e){for(var r=[],o=arguments.length-2;o-- >0;)r[o]=arguments[o+2];var n=this.getStoreSet(t,e);if(r.length>2)if(Array.isArray(r[0])){var i=r[2];this.checkTypeInLazyStore(e,i)||n.add(r)}else this.checkContentExist(r,n)||(this.logger("(addToStore) insert new",r),n.add(r));else n.add(r);return t.set(e,n),[t,n.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,o){if(void 0===o&&(o=null),this.logger('(addToNormalStore) try to add "'+e+'" --\x3e "'+t+'" to normal store'),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",'"'+e+'" --\x3e "'+t+'" can add to normal store');var n=this.hashFnToKey(r),i=[this.normalStore,t,n,r,o,e],s=Reflect.apply(this.addToStore,this,i),a=s[0],u=s[1];return this.normalStore=a,u}return!1},e.prototype.addToLazyStore=function(t,e,r,o){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===o&&(o=!1);var n=[this.lazyStore,t,this.toArray(e),r];o&&n.push(o);var i=Reflect.apply(this.addToStore,this,n),s=i[0],a=i[1];return this.lazyStore=s,this.logger("(addToLazyStore) size: "+a),a},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},o.normalStore.set=function(t){s.set(this,t)},o.normalStore.get=function(){return s.get(this)},o.lazyStore.set=function(t){a.set(this,t)},o.lazyStore.get=function(){return a.get(this)},Object.defineProperties(e.prototype,o),e}(function(t){function e(){t.call(this),this.__suspend_state__=null,this.__pattern__=null,this.queueStore=new Set}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$queues:{configurable:!0}};return e.prototype.$suspend=function(){this.logger("---\x3e SUSPEND ALL OPS <---"),this.__suspend__(!0)},e.prototype.$release=function(){this.logger("---\x3e RELEASE SUSPENDED QUEUE <---"),this.__suspend__(!1)},e.prototype.$suspendEvent=function(t){var e=function(t){switch(!0){case!0===o(t):return t;case!0===n(t):return new RegExp(t);default:return!1}}(t);if(o(e))return this.__pattern__=e,this.$suspend();throw new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof e+'" instead')},e.prototype.$queue=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];if(this.logger("($queue) get called"),!0===this.__suspend_state__){if(o(this.__pattern__)){var n=this.__pattern__.test(t);if(!n)return!1}this.logger("($queue) added to $queue",e),this.queueStore.add([t].concat(e))}return!!this.__suspend_state__},r.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},e.prototype.__suspend__=function(t){if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value! we got "+typeof t);var e=this.__suspend_state__;this.__suspend_state__=t,this.logger('($suspend) Change from "'+e+'" --\x3e "'+t+'"'),!0===e&&!1===t&&this.__release__()},e.prototype.__release__=function(){var t=this,e=this.queueStore.size,r=this.__pattern__;if(this.__pattern__=null,this.logger("(release) was called with "+e+(r?' for "'+r+'"':"")+" item"+(e>1?"s":"")),e>0){var o=Array.from(this.queueStore);this.queueStore.clear(),this.logger("(release queue)",o),o.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}return e},Object.defineProperties(e.prototype,r),e}(u))));exports.ALL_EVT="all",exports.AVAILABLE_EVTS=h,exports.CLEAR_EVT="clear",exports.DELETE_EVT="delete",exports.GET_EVT="get",exports.HAS_EVT="has",exports.JsonqlStore=p,exports.SET_EVT="set",exports.SIZE_EVT="size",exports.TAKE_EVT="take"; //# sourceMappingURL=jsonql-store.cjs.js.map diff --git a/packages/@jsonql/store/dist/jsonql-store.umd.js b/packages/@jsonql/store/dist/jsonql-store.umd.js index 2cce5300..7cc714c2 100644 --- a/packages/@jsonql/store/dist/jsonql-store.umd.js +++ b/packages/@jsonql/store/dist/jsonql-store.umd.js @@ -1,2 +1,2 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).jsonqlStore={})}(this,(function(t){"use strict";var e="You are trying to register an event already been taken by other type:",r=["on","only","once","onlyOnce"],o=["on","only"];function n(t){return t instanceof RegExp}function i(t){return"string"==typeof t}function s(t){if(i(t))throw new Error("Wrong type, we want number!");return!isNaN(parseInt(t))}var a=new WeakMap,u=new WeakMap,l=function(){},h={$name:{configurable:!0},is:{configurable:!0}};l.prototype.logger=function(){},h.$name.get=function(){return"to1source-event"},h.is.get=function(){return this.$name},l.prototype.validateEvt=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.forEach((function(e){if(!i(e))throw t.logger("(validateEvt)",e),new Error("Event name must be string type! we got "+typeof e)})),!0},l.prototype.validate=function(t,e){if(this.validateEvt(t)&&"function"==typeof e)return!0;throw new Error("callback required to be function type! we got "+typeof e)},l.prototype.validateType=function(t){return this.validateEvt(t),!!r.filter((function(e){return t===e})).length},l.prototype.run=function(t,e,r){return this.logger("(run) callback:",t,"payload:",e,"context:",r),this.$done=Reflect.apply(t,r,this.toArray(e)),this.$done},l.prototype.hashFnToKey=function(t){return function(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}(t.toString())+""},Object.defineProperties(l.prototype,h);var p=["has","set","get","delete","take","all","size","clear"],g=function(t){function e(e){void 0===e&&(e={}),t.call(this,e),this.$store=new Map}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={length:{configurable:!0}};return e.prototype.has=function(t){var e=this.$store.has(t)||!1;return this.$trigger("has",[t,e]),e},e.prototype.set=function(t,e){return this.$store.set(t,e),this.$trigger("set",[t,e]),this.has(t)},e.prototype.get=function(t){var e=this.$store.get(t)||!1;return this.$trigger("get",[t,e]),e},e.prototype.delete=function(t){var e=this.$store.delete(t);return this.$trigger("delete",[t,e]),e},e.prototype.take=function(t){if(this.has(t)){var e=this.$store.get(t);return this.$trigger("take",[t,e]),this.$store.delete(t),e}return this.$trigger("take",[t]),!1},e.prototype.all=function(t){void 0===t&&(t=!1);var e=this.$store.entries(),r=t?Array.from(e):e;return this.$trigger("all",[r]),r},e.prototype.size=function(){var t=this.$store.size;return this.$trigger("size",[t]),t},r.length.get=function(){return this.size()},e.prototype.clear=function(){this.$store.clear(),this.$trigger("clear")},e.prototype.on=function(t,e,r){if(void 0===r&&(r=null),!!p.filter((function(e){return e===t})).length)return this.$on(t,e,r);throw new Error(t+" is not one of ours!")},Object.defineProperties(e.prototype,r),e}(function(t){function r(e){void 0===e&&(e={}),t.call(this,e)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var o={$done:{configurable:!0}};return r.prototype.$on=function(t,r,o){var n=this;void 0===o&&(o=null);this.validate(t,r);var i=this.takeFromStore(t);if(!1===i)return this.logger('($on) "'+t+'" is not in lazy store'),this.addToNormalStore(t,"on",r,o);this.logger("($on) "+t+" found in lazy store");var s=0;return i.forEach((function(i){var a=i[0],u=i[1],l=i[2];if(l&&"on"!==l)throw new Error(e+" "+l);n.logger("($on)",'call run "'+t+'"'),n.run(r,a,o||u),s+=n.addToNormalStore(t,"on",r,o||u)})),this.logger("($on) return size "+s),s},r.prototype.$once=function(t,r,o){void 0===o&&(o=null),this.validate(t,r);var n=this.takeFromStore(t);if(!1===n)return this.logger('($once) "'+t+'" is not in the lazy store'),this.addToNormalStore(t,"once",r,o);this.logger("($once)",n);var i=Array.from(n)[0],s=i[0],a=i[1],u=i[2];if(u&&"once"!==u)throw new Error(e+" "+u);this.logger("($once)",'call run "'+t+'"'),this.run(r,s,o||a),this.$off(t)},r.prototype.$only=function(t,r,o){var n=this;void 0===o&&(o=null),this.validate(t,r);var i=!1,s=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger('($only) "'+t+'" add to normalStore'),i=this.addToNormalStore(t,"only",r,o)),!1!==s)&&(this.logger('($only) "'+t+'" found data in lazy store to execute'),Array.from(s).forEach((function(i){var s=i[0],a=i[1],u=i[2];if(u&&"only"!==u)throw new Error(e+" "+u);n.logger('($only) call run "'+t+'"'),n.run(r,s,o||a)})));return i},r.prototype.$onlyOnce=function(t,r,o){void 0===o&&(o=null),this.validate(t,r);var n=!1,i=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger('($onlyOnce) "'+t+'" add to normalStore'),n=this.addToNormalStore(t,"onlyOnce",r,o)),!1!==i){this.logger("($onlyOnce)",i);var s=Array.from(i)[0],a=s[0],u=s[1],l=s[2];if(l&&"onlyOnce"!==l)throw new Error(e+" "+l);this.logger('($onlyOnce) call run "'+t+'"'),this.run(r,a,o||u),this.$off(t)}return n},r.prototype.$max=function(t,e,r){if(void 0===r&&(r=null),this.validateEvt(t),s(e)&&e>0){if(!1!==this.$get(t,!0)){var o=this.searchMapEvt(t);if(o.length){var n=o[0][3],i=(this.checkMaxStore(t,e),this);return function(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];var s=i.getMaxStore(t),a=-1;if(s>0){var u=i.$call(t,n,r);if(Reflect.apply(u,i,e),-1===(a=i.checkMaxStore(t)))return i.$off(t),-1}return a}}}return this.logger("The "+t+" is not registered, can not execute non-existing event at the moment"),-1}throw new Error("Expect max to be an integer and greater than zero! But we got ["+typeof e+"]"+e+" instead")},r.prototype.$replace=function(t,e,r,o){if(void 0===r&&(r=null),void 0===o&&(o="on"),this.validateType(o)){this.$off(t);var n=this["$"+o];return this.logger("($replace)",t,e),Reflect.apply(n,this,[t,e,r])}throw new Error(o+" is not supported!")},r.prototype.$trigger=function(t,e,r,o){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===o&&(o=!1),this.validateEvt(t);var n=0,i=this.normalStore;if(this.logger("($trigger) normalStore",i),i.has(t)){if(this.logger('($trigger) "'+t+'" found'),this.$queue(t,e,r,o))return this.logger('($trigger) Currently suspended "'+t+'" added to queue, nothing executed. Exit now.'),!1;for(var s=Array.from(i.get(t)),a=s.length,u=!1,l=0;l0&&--r,!(r>0))return this.maxCountStore.delete(t),this.logger("remove "+t+" from maxStore"),-1;this.maxCountStore.set(t,r)}return r}throw new Error("Expect max to be an integer, but we got "+typeof e+" "+e)},e.prototype.searchMapEvt=function(t){var e=this.$get(t,!0).filter((function(t){var e,r=t[3];return e=r,!!o.filter((function(t){return e===t})).length}));return e.length?e:[]},e.prototype.takeFromStore=function(t,e){void 0===e&&(e="lazyStore");var r=this[e];if(r){if(this.logger("(takeFromStore)",e,r),r.has(t)){var o=r.get(t);return this.logger('(takeFromStore) has "'+t+'"',o),r.delete(t),o}return!1}throw new Error('"'+e+'" is not supported!')},e.prototype.findFromStore=function(t,e,r){return void 0===r&&(r=!1),!!e.has(t)&&Array.from(e.get(t)).map((function(t){return r?t:t[1]}))},e.prototype.removeFromStore=function(t,e){return!!e.has(t)&&(this.logger("($off)",t),e.delete(t),!0)},e.prototype.getStoreSet=function(t,e){var r;return t.has(e)?(this.logger('(addToStore) "'+e+'" existed'),r=t.get(e)):(this.logger('(addToStore) create new Set for "'+e+'"'),r=new Set),r},e.prototype.addToStore=function(t,e){for(var r=[],o=arguments.length-2;o-- >0;)r[o]=arguments[o+2];var n=this.getStoreSet(t,e);if(r.length>2)if(Array.isArray(r[0])){var i=r[2];this.checkTypeInLazyStore(e,i)||n.add(r)}else this.checkContentExist(r,n)||(this.logger("(addToStore) insert new",r),n.add(r));else n.add(r);return t.set(e,n),[t,n.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,o){if(void 0===o&&(o=null),this.logger('(addToNormalStore) try to add "'+e+'" --\x3e "'+t+'" to normal store'),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",'"'+e+'" --\x3e "'+t+'" can add to normal store');var n=this.hashFnToKey(r),i=[this.normalStore,t,n,r,o,e],s=Reflect.apply(this.addToStore,this,i),a=s[0],u=s[1];return this.normalStore=a,u}return!1},e.prototype.addToLazyStore=function(t,e,r,o){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===o&&(o=!1);var n=[this.lazyStore,t,this.toArray(e),r];o&&n.push(o);var i=Reflect.apply(this.addToStore,this,n),s=i[0],a=i[1];return this.lazyStore=s,this.logger("(addToLazyStore) size: "+a),a},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){a.set(this,t)},r.normalStore.get=function(){return a.get(this)},r.lazyStore.set=function(t){u.set(this,t)},r.lazyStore.get=function(){return u.get(this)},Object.defineProperties(e.prototype,r),e}(function(t){function e(){t.call(this),this.__suspend_state__=null,this.__pattern__=null,this.queueStore=new Set}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$queues:{configurable:!0}};return e.prototype.$suspend=function(){this.logger("---\x3e SUSPEND ALL OPS <---"),this.__suspend__(!0)},e.prototype.$release=function(){this.logger("---\x3e RELEASE SUSPENDED QUEUE <---"),this.__suspend__(!1)},e.prototype.$suspendEvent=function(t){var e=function(t){switch(!0){case!0===n(t):return t;case!0===i(t):return new RegExp(t);default:return!1}}(t);if(n(e))return this.__pattern__=e,this.$suspend();throw new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof e+'" instead')},e.prototype.$queue=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];if(this.logger("($queue) get called"),!0===this.__suspend_state__){if(n(this.__pattern__)){var o=this.__pattern__.test(t);if(!o)return!1}this.logger("($queue) added to $queue",e),this.queueStore.add([t].concat(e))}return!!this.__suspend_state__},r.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},e.prototype.__suspend__=function(t){if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value! we got "+typeof t);var e=this.__suspend_state__;this.__suspend_state__=t,this.logger('($suspend) Change from "'+e+'" --\x3e "'+t+'"'),!0===e&&!1===t&&this.__release__()},e.prototype.__release__=function(){var t=this,e=this.queueStore.size,r=this.__pattern__;if(this.__pattern__=null,this.logger("(release) was called with "+e+(r?' for "'+r+'"':"")+" item"+(e>1?"s":"")),e>0){var o=Array.from(this.queueStore);this.queueStore.clear(),this.logger("(release queue)",o),o.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}return e},Object.defineProperties(e.prototype,r),e}(l))));t.ALL_EVT="all",t.AVAILABLE_EVTS=p,t.CLEAR_EVT="clear",t.DELETE_EVT="delete",t.GET_EVT="get",t.HAS_EVT="has",t.JsonqlStore=g,t.SET_EVT="set",t.SIZE_EVT="size",t.TAKE_EVT="take",Object.defineProperty(t,"__esModule",{value:!0})})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).jsonqlStore={})}(this,(function(t){"use strict";var e="You are trying to register an event already been taken by other type:",r=["on","only","once","onlyOnce"],o=["on","only"];function n(t){return t instanceof RegExp}function i(t){return"string"==typeof t}function s(t){if(i(t))throw new Error("Wrong type, we want number!");return!isNaN(parseInt(t))}var a=new WeakMap,u=new WeakMap,l=function(){},h={$name:{configurable:!0},is:{configurable:!0}};l.prototype.logger=function(){},h.$name.get=function(){return"to1source-event"},h.is.get=function(){return this.$name},l.prototype.validateEvt=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.forEach((function(e){if(!i(e))throw t.logger("(validateEvt)",e),new Error("Event name must be string type! we got "+typeof e)})),!0},l.prototype.validate=function(t,e){if(this.validateEvt(t)&&"function"==typeof e)return!0;throw new Error("callback required to be function type! we got "+typeof e)},l.prototype.validateType=function(t){return this.validateEvt(t),!!r.filter((function(e){return t===e})).length},l.prototype.run=function(t,e,r){return this.logger("(run) callback:",t,"payload:",e,"context:",r),this.$done=Reflect.apply(t,r,this.toArray(e)),this.$done},l.prototype.hashFnToKey=function(t){return function(t){return t.split("").reduce((function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t}),0)}(t.toString())+""},Object.defineProperties(l.prototype,h);var p=["has","set","get","delete","take","all","size","clear"],f=function(t){function e(e){void 0===e&&(e={}),t.call(this,e),this.__eventOff=!!e.eventOff,this.$store=new Map}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={length:{configurable:!0}};return e.prototype.__emit=function(t,e){if(!1===this.__eventOff)return this.$trigger(t,e)},e.prototype.__wrap=function(t){return t},e.prototype.__unwrap=function(t){return t},e.prototype.has=function(t){var e=this.$store.has(t)||!1;return this.__emit("has",[t,e]),e},e.prototype.set=function(t,e){return this.$store.set(t,e),this.__emit("set",[t,e]),this.has(t)},e.prototype.get=function(t){var e=this.$store.get(t)||!1;return this.__emit("get",[t,e]),e},e.prototype.delete=function(t){var e=this.$store.delete(t);return this.__emit("delete",[t,e]),e},e.prototype.take=function(t){if(this.has(t)){var e=this.$store.get(t);return this.__emit("take",[t,e]),this.$store.delete(t),e}return this.__emit("take",[t]),!1},e.prototype.all=function(t){void 0===t&&(t=!0);var e=this.offload(),r=t?Array.from(e):e;return this.__emit("all",[r]),r},e.prototype.offload=function(){return this.$store.entries()},e.prototype.size=function(){var t=this.$store.size;return this.__emit("size",[t]),t},r.length.get=function(){return this.size()},e.prototype.clear=function(){this.$store.clear(),this.__emit("clear")},e.prototype.on=function(t,e,r){if(void 0===r&&(r=null),!1===this.__eventOff){if(!!p.filter((function(e){return e===t})).length)return this.$on(t,e,r);throw new Error(t+" is not one of ours!")}},Object.defineProperties(e.prototype,r),e}(function(t){function r(e){void 0===e&&(e={}),t.call(this,e)}t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r;var o={$done:{configurable:!0}};return r.prototype.$on=function(t,r,o){var n=this;void 0===o&&(o=null);this.validate(t,r);var i=this.takeFromStore(t);if(!1===i)return this.logger('($on) "'+t+'" is not in lazy store'),this.addToNormalStore(t,"on",r,o);this.logger("($on) "+t+" found in lazy store");var s=0;return i.forEach((function(i){var a=i[0],u=i[1],l=i[2];if(l&&"on"!==l)throw new Error(e+" "+l);n.logger("($on)",'call run "'+t+'"'),n.run(r,a,o||u),s+=n.addToNormalStore(t,"on",r,o||u)})),this.logger("($on) return size "+s),s},r.prototype.$once=function(t,r,o){void 0===o&&(o=null),this.validate(t,r);var n=this.takeFromStore(t);if(!1===n)return this.logger('($once) "'+t+'" is not in the lazy store'),this.addToNormalStore(t,"once",r,o);this.logger("($once)",n);var i=Array.from(n)[0],s=i[0],a=i[1],u=i[2];if(u&&"once"!==u)throw new Error(e+" "+u);this.logger("($once)",'call run "'+t+'"'),this.run(r,s,o||a),this.$off(t)},r.prototype.$only=function(t,r,o){var n=this;void 0===o&&(o=null),this.validate(t,r);var i=!1,s=this.takeFromStore(t);(this.normalStore.has(t)||(this.logger('($only) "'+t+'" add to normalStore'),i=this.addToNormalStore(t,"only",r,o)),!1!==s)&&(this.logger('($only) "'+t+'" found data in lazy store to execute'),Array.from(s).forEach((function(i){var s=i[0],a=i[1],u=i[2];if(u&&"only"!==u)throw new Error(e+" "+u);n.logger('($only) call run "'+t+'"'),n.run(r,s,o||a)})));return i},r.prototype.$onlyOnce=function(t,r,o){void 0===o&&(o=null),this.validate(t,r);var n=!1,i=this.takeFromStore(t);if(this.normalStore.has(t)||(this.logger('($onlyOnce) "'+t+'" add to normalStore'),n=this.addToNormalStore(t,"onlyOnce",r,o)),!1!==i){this.logger("($onlyOnce)",i);var s=Array.from(i)[0],a=s[0],u=s[1],l=s[2];if(l&&"onlyOnce"!==l)throw new Error(e+" "+l);this.logger('($onlyOnce) call run "'+t+'"'),this.run(r,a,o||u),this.$off(t)}return n},r.prototype.$max=function(t,e,r){if(void 0===r&&(r=null),this.validateEvt(t),s(e)&&e>0){if(!1!==this.$get(t,!0)){var o=this.searchMapEvt(t);if(o.length){var n=o[0][3],i=(this.checkMaxStore(t,e),this);return function(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];var s=i.getMaxStore(t),a=-1;if(s>0){var u=i.$call(t,n,r);if(Reflect.apply(u,i,e),-1===(a=i.checkMaxStore(t)))return i.$off(t),-1}return a}}}return this.logger("The "+t+" is not registered, can not execute non-existing event at the moment"),-1}throw new Error("Expect max to be an integer and greater than zero! But we got ["+typeof e+"]"+e+" instead")},r.prototype.$replace=function(t,e,r,o){if(void 0===r&&(r=null),void 0===o&&(o="on"),this.validateType(o)){this.$off(t);var n=this["$"+o];return this.logger("($replace)",t,e),Reflect.apply(n,this,[t,e,r])}throw new Error(o+" is not supported!")},r.prototype.$trigger=function(t,e,r,o){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===o&&(o=!1),this.validateEvt(t);var n=0,i=this.normalStore;if(this.logger("($trigger) normalStore",i),i.has(t)){if(this.logger('($trigger) "'+t+'" found'),this.$queue(t,e,r,o))return this.logger('($trigger) Currently suspended "'+t+'" added to queue, nothing executed. Exit now.'),!1;for(var s=Array.from(i.get(t)),a=s.length,u=!1,l=0;l0&&--r,!(r>0))return this.maxCountStore.delete(t),this.logger("remove "+t+" from maxStore"),-1;this.maxCountStore.set(t,r)}return r}throw new Error("Expect max to be an integer, but we got "+typeof e+" "+e)},e.prototype.searchMapEvt=function(t){var e=this.$get(t,!0).filter((function(t){var e,r=t[3];return e=r,!!o.filter((function(t){return e===t})).length}));return e.length?e:[]},e.prototype.takeFromStore=function(t,e){void 0===e&&(e="lazyStore");var r=this[e];if(r){if(this.logger("(takeFromStore)",e,r),r.has(t)){var o=r.get(t);return this.logger('(takeFromStore) has "'+t+'"',o),r.delete(t),o}return!1}throw new Error('"'+e+'" is not supported!')},e.prototype.findFromStore=function(t,e,r){return void 0===r&&(r=!1),!!e.has(t)&&Array.from(e.get(t)).map((function(t){return r?t:t[1]}))},e.prototype.removeFromStore=function(t,e){return!!e.has(t)&&(this.logger("($off)",t),e.delete(t),!0)},e.prototype.getStoreSet=function(t,e){var r;return t.has(e)?(this.logger('(addToStore) "'+e+'" existed'),r=t.get(e)):(this.logger('(addToStore) create new Set for "'+e+'"'),r=new Set),r},e.prototype.addToStore=function(t,e){for(var r=[],o=arguments.length-2;o-- >0;)r[o]=arguments[o+2];var n=this.getStoreSet(t,e);if(r.length>2)if(Array.isArray(r[0])){var i=r[2];this.checkTypeInLazyStore(e,i)||n.add(r)}else this.checkContentExist(r,n)||(this.logger("(addToStore) insert new",r),n.add(r));else n.add(r);return t.set(e,n),[t,n.size]},e.prototype.checkContentExist=function(t,e){return!!Array.from(e).filter((function(e){return e[0]===t[0]})).length},e.prototype.checkTypeInStore=function(t,e){this.validateEvt(t,e);var r=this.$get(t,!0);return!1===r||!r.filter((function(t){var r=t[3];return e!==r})).length},e.prototype.checkTypeInLazyStore=function(t,e){this.validateEvt(t,e);var r=this.lazyStore.get(t);return this.logger("(checkTypeInLazyStore)",r),!!r&&!!Array.from(r).filter((function(t){return t[2]!==e})).length},e.prototype.addToNormalStore=function(t,e,r,o){if(void 0===o&&(o=null),this.logger('(addToNormalStore) try to add "'+e+'" --\x3e "'+t+'" to normal store'),this.checkTypeInStore(t,e)){this.logger("(addToNormalStore)",'"'+e+'" --\x3e "'+t+'" can add to normal store');var n=this.hashFnToKey(r),i=[this.normalStore,t,n,r,o,e],s=Reflect.apply(this.addToStore,this,i),a=s[0],u=s[1];return this.normalStore=a,u}return!1},e.prototype.addToLazyStore=function(t,e,r,o){void 0===e&&(e=[]),void 0===r&&(r=null),void 0===o&&(o=!1);var n=[this.lazyStore,t,this.toArray(e),r];o&&n.push(o);var i=Reflect.apply(this.addToStore,this,n),s=i[0],a=i[1];return this.lazyStore=s,this.logger("(addToLazyStore) size: "+a),a},e.prototype.toArray=function(t){return Array.isArray(t)?t:[t]},r.normalStore.set=function(t){a.set(this,t)},r.normalStore.get=function(){return a.get(this)},r.lazyStore.set=function(t){u.set(this,t)},r.lazyStore.get=function(){return u.get(this)},Object.defineProperties(e.prototype,r),e}(function(t){function e(){t.call(this),this.__suspend_state__=null,this.__pattern__=null,this.queueStore=new Set}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={$queues:{configurable:!0}};return e.prototype.$suspend=function(){this.logger("---\x3e SUSPEND ALL OPS <---"),this.__suspend__(!0)},e.prototype.$release=function(){this.logger("---\x3e RELEASE SUSPENDED QUEUE <---"),this.__suspend__(!1)},e.prototype.$suspendEvent=function(t){var e=function(t){switch(!0){case!0===n(t):return t;case!0===i(t):return new RegExp(t);default:return!1}}(t);if(n(e))return this.__pattern__=e,this.$suspend();throw new Error('We expect a pattern variable to be string or RegExp, but we got "'+typeof e+'" instead')},e.prototype.$queue=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];if(this.logger("($queue) get called"),!0===this.__suspend_state__){if(n(this.__pattern__)){var o=this.__pattern__.test(t);if(!o)return!1}this.logger("($queue) added to $queue",e),this.queueStore.add([t].concat(e))}return!!this.__suspend_state__},r.$queues.get=function(){var t=this.queueStore.size;return this.logger("($queues)","size: "+t),t>0?Array.from(this.queueStore):[]},e.prototype.__suspend__=function(t){if("boolean"!=typeof t)throw new Error("$suspend only accept Boolean value! we got "+typeof t);var e=this.__suspend_state__;this.__suspend_state__=t,this.logger('($suspend) Change from "'+e+'" --\x3e "'+t+'"'),!0===e&&!1===t&&this.__release__()},e.prototype.__release__=function(){var t=this,e=this.queueStore.size,r=this.__pattern__;if(this.__pattern__=null,this.logger("(release) was called with "+e+(r?' for "'+r+'"':"")+" item"+(e>1?"s":"")),e>0){var o=Array.from(this.queueStore);this.queueStore.clear(),this.logger("(release queue)",o),o.forEach((function(e){t.logger(e),Reflect.apply(t.$trigger,t,e)})),this.logger("Release size "+this.queueStore.size)}return e},Object.defineProperties(e.prototype,r),e}(l))));t.ALL_EVT="all",t.AVAILABLE_EVTS=p,t.CLEAR_EVT="clear",t.DELETE_EVT="delete",t.GET_EVT="get",t.HAS_EVT="has",t.JsonqlStore=f,t.SET_EVT="set",t.SIZE_EVT="size",t.TAKE_EVT="take",Object.defineProperty(t,"__esModule",{value:!0})})); //# sourceMappingURL=jsonql-store.umd.js.map diff --git a/packages/@jsonql/store/package.json b/packages/@jsonql/store/package.json index ccb82822..998afdfb 100644 --- a/packages/@jsonql/store/package.json +++ b/packages/@jsonql/store/package.json @@ -12,7 +12,8 @@ "build:cjs": "TARGET=cjs rollup -c", "build:umd": "TARGET=umd rollup -c", "test:basic": "DEBUG=jsonql-store* ava ./tests/basic.test.js", - "test:event": "DEBUG=jsonql-store* ava ./tests/event.test.js" + "test:event": "DEBUG=jsonql-store* ava ./tests/event.test.js", + "test:off": "DEBUG=jsonql-store* ava ./tests/event-off.test.js" }, "keywords": [ "store", diff --git a/packages/@jsonql/store/tests/event-off.test.js b/packages/@jsonql/store/tests/event-off.test.js index 1fe32401..76b74af9 100644 --- a/packages/@jsonql/store/tests/event-off.test.js +++ b/packages/@jsonql/store/tests/event-off.test.js @@ -2,10 +2,15 @@ const test = require('ava') const { JsonqlStore } = require('../dist/jsonql-store.cjs') +const logger = require('debug')('jsonql-store:test:event-off') + test(`Testing the event off`, t => { - + const store = new JsonqlStore({ eventOff: true, logger }) + + const evt = store.on('some-event', () => {}) + t.is(evt, undefined) }) \ No newline at end of file -- Gitee From e2f445a2025efae2f4e9498d4ce01eb61b815888 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 10:02:54 +0800 Subject: [PATCH 05/18] update README with full documentation --- packages/@jsonql/store/README.md | 162 +++++++++++++++++++++++++++++-- 1 file changed, 152 insertions(+), 10 deletions(-) diff --git a/packages/@jsonql/store/README.md b/packages/@jsonql/store/README.md index ccc99b65..b243690d 100644 --- a/packages/@jsonql/store/README.md +++ b/packages/@jsonql/store/README.md @@ -1,6 +1,6 @@ # @jsonql/store -This is a VERY simple in-memory store with a event hook. +> A super simple in-memory store with an event hook What that mean is, whenever you call this store, you can hook into it by listen to the event, and do your thing; such as return value from the store of your own choice, save value to your store etc. @@ -29,7 +29,7 @@ cache.$on(SET_EVT, function(value) { ## API -This module export the follow: +This module exports the follow: - JsonqlStore - HAS_EVT @@ -59,21 +59,163 @@ const store = new JsonqlStore({ logger }) ``` -### store.has HAS_EVT +#### Init options -### store.set SET_EVT +##### logger: allow you to pass a logging function -### store.get GET_EVT -### store.delete DELETE_EVT +```js +// store.js +const debug = require('debug')('a-key-to-id-your-logger') +const { JsonqlStore } = require('@jsonql/store') -### store.take TAKE_EVT +const store = new JsonqlStore({ logger }) + +``` + +Then when you run it like: + +```sh +$ DEBUG=a-key-to-id-your-logger node ./store.js +``` + +You will see a lot of output from your console, that show what is going on internally. + +##### eventOff: turn off the event listener + +You can turn off the event listener + +```js +const { JsonqlStore, SET_EVT } = require('@jsonql/store') +const store = new JsonqlStore({ eventOff: true}) + +// if you try to listen to the event +const isEventOn = store.on(SET_EVT, function somecallback() {}) + +``` + +In the above example, the on will do nothing, `isEventOn` is `undefined` + +For more about the it's parent the [@to1source/event](https://npmjs.com/package/@to1source/event), please check their documentation. + +### store.on(eventName, callback) + +Allow you to listen to the event happening inside, it's better using the exported constants as event name + +```js +const { JsonqlStore, SET_EVT } = require('@jsonql/store') +const store = new JsonqlStore() + +store.set('some-key', 'some-value') + +// the magic is we don't care about when you start listening +store.on(SET_EVT, function(value) { + // you will get back the key and value + // also you can add as many event listener as you need to +}) + +``` + +### store.has(key) HAS_EVT + +Check if if certain key existed in the store + +```js -### store.all ALL_EVT +const check = store.has(key) +// listen to this event +store.on(HAS_EVT, function(value) { + // you will get back the key and the check value +}) + +``` + +### store.set(key,value) SET_EVT + +Store data id by key (key can be anything) + +```js +store.set('some-key', 'some-value') +store.on(SET_EVT, function(result) { + // get back the key and value in an array +}) + +``` -### store.size SIZE_EVT (alias JsonqlStore.length) +### store.get(key) GET_EVT -### store.clear CLEAR_EVT +Get the data id by key + +```js +const data = store.get('some-key') +store.on(GET_EVT, function(result) { + // get back the key and value in an array +}) + +``` + +### store.delete(key) DELETE_EVT + +Delete data id by key + +```js +const result = store.delete('some-key') +store.on(DELETE_EVT, function(result) { + // get back the key and value in an array +}) + +``` + +### store.take(key) TAKE_EVT + +Get the data id by key, then remove it from the store + +```js +const result = store.take('some-key') +store.on(TAKE_EVT, function(result) { + // get back the key and value in an array +}) +const existed = store.has('some-key') +// existed is false +``` + +### store.all(arr=true) ALL_EVT + +Return everything from the store as an array, if you pass `arr=false` then return the raw `Map` object + +```js +const result = store.all() +// it's an array so you can perform your ops here +result.map(x => console.log(x)) + +``` + +### store.size() SIZE_EVT (alias JsonqlStore.length) + +Return the size (how many) of the store + +```js +store.set('a', 1) +store.set('b', 2) +store.set('c', 3) + +const ctn = store.size() // it will be 3 + +store.length === ctn // same as above + +``` + + +### store.clear() CLEAR_EVT + +Clear out everything from the store + +```js +store.clear() +const check = store.all() +store.length === 0 + +``` --- -- Gitee From 877c1d50c91e09d064f25eb021cef3f9bb05311e Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 10:20:04 +0800 Subject: [PATCH 06/18] update deps and re-test --- packages/@jsonql/security/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/@jsonql/security/package.json b/packages/@jsonql/security/package.json index cb30230b..d19173b6 100644 --- a/packages/@jsonql/security/package.json +++ b/packages/@jsonql/security/package.json @@ -38,7 +38,7 @@ "author": "Joel Chu ", "license": "ISC", "dependencies": { - "@jsonql/store": "^0.9.0", + "@jsonql/store": "^0.9.1", "colors": "^1.4.0", "fs-extra": "^9.0.0", "jsonql-constants": "^2.0.14", -- Gitee From a56b07b005673c2bd2a7048fee17c880bcd6495d Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 10:25:41 +0800 Subject: [PATCH 07/18] @jsonql/security 0.9.5 --- packages/@jsonql/security/main.js | 6 ++--- packages/@jsonql/security/package.json | 2 +- .../security/src/cache/csrf-methods.js | 22 +++++++++++-------- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/packages/@jsonql/security/main.js b/packages/@jsonql/security/main.js index 9089f86d..ac68b36e 100644 --- a/packages/@jsonql/security/main.js +++ b/packages/@jsonql/security/main.js @@ -19,8 +19,7 @@ const { const { getCache, isCacheObj, - isNodeCache, - getNodeCache, + getToken, createCSRFToken, isCSRFTokenExist @@ -48,8 +47,7 @@ module.exports = { // new csrf and node cache related stuff getCache, isCacheObj, - isNodeCache, - getNodeCache, + getToken, createCSRFToken, isCSRFTokenExist diff --git a/packages/@jsonql/security/package.json b/packages/@jsonql/security/package.json index d19173b6..8ce6a65d 100644 --- a/packages/@jsonql/security/package.json +++ b/packages/@jsonql/security/package.json @@ -1,6 +1,6 @@ { "name": "@jsonql/security", - "version": "0.9.4", + "version": "0.9.5", "description": "jwt authentication helpers library for jsonql browser / node", "main": "main.js", "module": "index.js", diff --git a/packages/@jsonql/security/src/cache/csrf-methods.js b/packages/@jsonql/security/src/cache/csrf-methods.js index 53c61841..0fc533ba 100644 --- a/packages/@jsonql/security/src/cache/csrf-methods.js +++ b/packages/@jsonql/security/src/cache/csrf-methods.js @@ -5,6 +5,18 @@ const { JsonqlError } = require('jsonql-errors') // const store = getNodeCache() const STORE_FAIL_ERR = 'unable to store the token in node cache!' const { getCache, isCacheObj } = require('./get-cache') + +/** + * Check if the key existed + * @param {object} store the nodeCache + * @param {string} token token to check + * @return {boolean} + */ +function isCSRFTokenExist(store, token) { + return store.has(token) +} + + /** * Generate a token and check if it's in the store * @param {object} store explicitly pass the store instead of using the global one @@ -37,15 +49,7 @@ function createCSRFToken(store) { throw new JsonqlError('createCSRFToken', STORE_FAIL_ERR) } -/** - * Check if the key existed - * @param {object} store the nodeCache - * @param {string} token token to check - * @return {boolean} - */ -function isCSRFTokenExist(store, token) { - return store.has(token) -} + module.exports = { getToken, createCSRFToken, isCSRFTokenExist } -- Gitee From b3a81e271abfc46d45c183540ff4da1aca570a9d Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 10:40:27 +0800 Subject: [PATCH 08/18] update with the new getCache method --- packages/resolver/package.json | 2 +- packages/resolver/src/cache.js | 4 ++-- packages/resolver/src/client/clients-generator.js | 3 ++- packages/resolver/tests/combine.test.js | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/resolver/package.json b/packages/resolver/package.json index 3795e59b..391ef0c3 100644 --- a/packages/resolver/package.json +++ b/packages/resolver/package.json @@ -34,7 +34,7 @@ "url": "https://gitee.com/to1source/jsonql/issues" }, "dependencies": { - "@jsonql/security": "^0.9.4", + "@jsonql/security": "^0.9.5", "debug": "^4.1.1", "jsonql-constants": "^2.0.14", "jsonql-errors": "^1.2.1", diff --git a/packages/resolver/src/cache.js b/packages/resolver/src/cache.js index 91f55f9b..4277eed1 100644 --- a/packages/resolver/src/cache.js +++ b/packages/resolver/src/cache.js @@ -21,7 +21,7 @@ const { isCacheObj } = require('@jsonql/security') function getCacheResolver(key, store) { if (isCacheObj(store)) { - return store.$has(key) ? store.$get(key) : false + return store.has(key) ? store.get(key) : false } return false @@ -42,7 +42,7 @@ function cacheResolver(store) { */ return function cacheResolverAction(resolverName, resolver) { // the set return true on success, then we return the resolver for use next - return store.$set(resolverName, resolver) ? resolver : false + return store.set(resolverName, resolver) ? resolver : false } } diff --git a/packages/resolver/src/client/clients-generator.js b/packages/resolver/src/client/clients-generator.js index 2aa64dff..0f4308f6 100755 --- a/packages/resolver/src/client/clients-generator.js +++ b/packages/resolver/src/client/clients-generator.js @@ -12,7 +12,8 @@ const NAME_PROP = 'name' function clientsGenerator(clientConfigs) { return Promise.all( clientConfigs.map(clientConfig => { - let name = clientConfig.name; + let name = clientConfig.name + // @TODO we need to cache it somewhere return jsonqlNodeClient(clientConfig) .then(client => injectToFn(client, NAME_PROP, name)) }) diff --git a/packages/resolver/tests/combine.test.js b/packages/resolver/tests/combine.test.js index b72e1027..3bb7aaf6 100644 --- a/packages/resolver/tests/combine.test.js +++ b/packages/resolver/tests/combine.test.js @@ -32,7 +32,7 @@ test(`Testing the basic cache function first`, t => { test(`Test the nodeCache interface`, t => { const cache = t.context.cacheInstance - const result = cache.$set('some-key', 'some-value') + const result = cache.set('some-key', 'some-value') t.true(result) }) -- Gitee From cf1059fdbb573249f2b70b9e6a1d5a2d6fa64c11 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 10:59:35 +0800 Subject: [PATCH 09/18] jsonql-resolver 1.2.5 --- packages/resolver/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/resolver/package.json b/packages/resolver/package.json index 391ef0c3..aa5bd9ca 100644 --- a/packages/resolver/package.json +++ b/packages/resolver/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-resolver", - "version": "1.2.4", + "version": "1.2.5", "description": "This is NOT for general use, please do not install it directly. This module is part of the jsonql tools supporting modules.", "main": "index.js", "files": [ -- Gitee From 9e726fc3be7715951ad2967844b4e5e0e64f2fae Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 11:07:39 +0800 Subject: [PATCH 10/18] update the wrong constants names --- packages/ws-server-core/package.json | 4 ++-- packages/ws-server-core/src/options/props.js | 10 +++++----- packages/ws-server-core/tests/fn.test.js | 2 ++ 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/packages/ws-server-core/package.json b/packages/ws-server-core/package.json index 0e254b1a..447c65a3 100644 --- a/packages/ws-server-core/package.json +++ b/packages/ws-server-core/package.json @@ -27,7 +27,7 @@ "author": "Joel Chu ", "license": "MIT", "dependencies": { - "@jsonql/security": "^0.9.4", + "@jsonql/security": "^0.9.5", "@to1source/event": "^1.1.1", "colors": "^1.4.0", "debug": "^4.1.1", @@ -36,7 +36,7 @@ "jsonql-constants": "^2.0.14", "jsonql-errors": "^1.2.1", "jsonql-params-validator": "^1.6.2", - "jsonql-resolver": "^1.2.4", + "jsonql-resolver": "^1.2.5", "jsonql-utils": "^1.2.6", "lodash": "^4.17.15" }, diff --git a/packages/ws-server-core/src/options/props.js b/packages/ws-server-core/src/options/props.js index 2d6d0f58..fbac85b2 100644 --- a/packages/ws-server-core/src/options/props.js +++ b/packages/ws-server-core/src/options/props.js @@ -32,8 +32,8 @@ const { INIT_CONNECTION_FN_NAME, DISCONNECT_FN_NAME, SWITCH_USER_FN_NAME, - LOGIN_NAME, - LOGOUT_NAME, + LOGIN_FN_NAME, + LOGOUT_FN_NAME, CSRF_PROP_KEY } = require('jsonql-constants') @@ -61,8 +61,8 @@ const wsBaseOptions = { keysDir: createConfig(join(dirname, DEFAULT_KEYS_DIR), [STRING_TYPE]), // @0.6.0 expect this to be the path to the interComEventHandler to handle the INTER_COM_EVENT_NAMES initConnectionHandlerName: createConfig(INIT_CONNECTION_FN_NAME, [STRING_TYPE]), - loginHandlerName: createConfig(LOGIN_NAME, [STRING_TYPE]), - logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]), + loginHandlerName: createConfig(LOGIN_FN_NAME, [STRING_TYPE]), + logoutHandlerName: createConfig(LOGOUT_FN_NAME, [STRING_TYPE]), disconnectHandlerName: createConfig(DISCONNECT_FN_NAME, [STRING_TYPE]), switchUserHandlerName: createConfig(SWITCH_USER_FN_NAME, [STRING_TYPE]), // this is for construct the namespace @@ -85,7 +85,7 @@ const wsBaseOptions = { // we have to create a standlone prop to check if the user pass the socket server config first const socketAppProps = { - [SOCKET_TYPE_KEY]: createConfig(SOCKET_IO, [STRING_TYPE], { + [SOCKET_TYPE_PROP_KEY]: createConfig(SOCKET_IO, [STRING_TYPE], { [ALIAS_KEY]: SOCKET_TYPE_SERVER_ALIAS }) } diff --git a/packages/ws-server-core/tests/fn.test.js b/packages/ws-server-core/tests/fn.test.js index 002e11a6..c2aefd50 100644 --- a/packages/ws-server-core/tests/fn.test.js +++ b/packages/ws-server-core/tests/fn.test.js @@ -55,6 +55,8 @@ test.only(`test the get-socket-resolver method mainly to look at the cache`, asy console.info(str) } + debug(`config`, config) + const _params = [ 'jsonql', 'chatroom', -- Gitee From c62a46d8b2067500a3dcd46d344185c2e1d27db9 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 11:10:48 +0800 Subject: [PATCH 11/18] this is a really weird sitatuion --- packages/ws-server-core/src/options/index.js | 2 +- packages/ws-server-core/src/options/props.js | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/ws-server-core/src/options/index.js b/packages/ws-server-core/src/options/index.js index 6c04c171..f04878ce 100644 --- a/packages/ws-server-core/src/options/index.js +++ b/packages/ws-server-core/src/options/index.js @@ -50,7 +50,7 @@ function localCheckConfig(config) { } /** - * Wrapper method to check if there is already a nodeCache object, if not init a new one + * Wrapper method to check if there is already a cache object, if not init a new one * @param {object} opts configuration * @return {object} node cache instance */ diff --git a/packages/ws-server-core/src/options/props.js b/packages/ws-server-core/src/options/props.js index fbac85b2..85ac944b 100644 --- a/packages/ws-server-core/src/options/props.js +++ b/packages/ws-server-core/src/options/props.js @@ -26,7 +26,7 @@ const { DEFAULT_CONTRACT_DIR, DEFAULT_KEYS_DIR, - SOCKET_TYPE_KEY, + SOCKET_TYPE_PROP_KEY, SOCKET_TYPE_SERVER_ALIAS, INIT_CONNECTION_FN_NAME, @@ -78,8 +78,7 @@ const wsBaseOptions = { serverInitOption: createConfig({}, [OBJECT_TYPE]), // placeholder for now [CSRF_PROP_KEY]: createConfig('', [STRING_TYPE]), - // add this switch so we can test out the effects nodeCache is a fucking joke - // do not turn this on, because it can't store a complex object + // if we want to cache the resolver or not enableCacheResolver: createConfig(true, [BOOLEAN_TYPE]) } -- Gitee From a08cfd5cbf0bde0c24b7eb34b8947a1cf153b859 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 12:32:44 +0800 Subject: [PATCH 12/18] going back to the resolver to check what is the problem --- packages/resolver/src/cache.js | 2 +- ...solver.js => get-complete-socket-resolver.js} | 16 ++++++++++------ packages/resolver/src/get-socket-interceptor.js | 8 +++++--- packages/ws-server-core/src/options/index.js | 5 +++-- packages/ws-server-core/src/options/props.js | 11 ++++++----- .../ws-server-core/src/resolver/get-injectors.js | 2 +- .../src/resolver/resolve-socket-method.js | 12 +++++------- 7 files changed, 31 insertions(+), 25 deletions(-) rename packages/resolver/src/{combine-resolver.js => get-complete-socket-resolver.js} (85%) diff --git a/packages/resolver/src/cache.js b/packages/resolver/src/cache.js index 4277eed1..e76db89d 100644 --- a/packages/resolver/src/cache.js +++ b/packages/resolver/src/cache.js @@ -19,7 +19,7 @@ const { isCacheObj } = require('@jsonql/security') * @return {*} false when not found */ function getCacheResolver(key, store) { - if (isCacheObj(store)) { + if (key && isCacheObj(store)) { return store.has(key) ? store.get(key) : false } diff --git a/packages/resolver/src/combine-resolver.js b/packages/resolver/src/get-complete-socket-resolver.js similarity index 85% rename from packages/resolver/src/combine-resolver.js rename to packages/resolver/src/get-complete-socket-resolver.js index 588940b1..9414b5b8 100644 --- a/packages/resolver/src/combine-resolver.js +++ b/packages/resolver/src/get-complete-socket-resolver.js @@ -1,7 +1,7 @@ // combine-resolver with cache and injectors const { SOCKET_NAME } = require('jsonql-constants') const { chainFns } = require('jsonql-utils') -const { isString } = require('jsonql-params-validator') +// const { isString } = require('jsonql-params-validator') const { getCacheResolver, cacheResolver } = require('./cache') const { getResolver } = require('./resolve-methods') @@ -28,18 +28,22 @@ const debug = require('debug')('jsonql-resolver:combine-resolver') function getCompleteSocketResolver(resolverName, opts, key = null, store = null) { // the contract is within the opts const { contract } = opts - const fn = getResolver(resolverName, SOCKET_NAME, contract, opts) + let resolver // [deliverFn, resolverName, args, opts, ws, userdata] - if (isString(key) && store !== null) { + if (key && store !== null) { debug('use cache resolver with key', key) + resolver = getCacheResolver(key, store) if (resolver !== false) { - debug('return the cache version with key', key, resolver.toString()) + debug('return the cache version with key', key, resolver) return resolver } } + + const resolverFn = getResolver(resolverName, SOCKET_NAME, contract, opts) + /** * @param {array} injectors to run through the injection * @param {array<*>} params then we add the resolver at the end to pass through the injectors @@ -48,9 +52,9 @@ function getCompleteSocketResolver(resolverName, opts, key = null, store = null) return function runInjectors(injectors, params) { const executor = Reflect.apply(chainFns, null, injectors) // please note the final injector must return just the resolver - const resolver = Reflect.apply(executor, null, [fn, ...params]) + const resolver = Reflect.apply(executor, null, [resolverFn, ...params]) - if (isString(key) && store !== null) { + if (key && store !== null) { const cacher = cacheResolver(store) return cacher(key, resolver) diff --git a/packages/resolver/src/get-socket-interceptor.js b/packages/resolver/src/get-socket-interceptor.js index 57e9d19e..9020cb31 100644 --- a/packages/resolver/src/get-socket-interceptor.js +++ b/packages/resolver/src/get-socket-interceptor.js @@ -16,9 +16,11 @@ const { LOGOUT_FN_NAME_PROP_KEY, DISCONNECT_FN_NAME_PROP_KEY } = require('jsonql-constants') -const { JsonqlResolverAppError, JsonqlResolverNotFoundError } = require('jsonql-errors') -const { validateAsync, isString } = require('jsonql-params-validator') -// const { isCacheObj } = require('@jsonql/security') +const { + JsonqlResolverAppError, + JsonqlResolverNotFoundError +} = require('jsonql-errors') +const { validateAsync } = require('jsonql-params-validator') const { getCacheResolver, cacheResolver } = require('./cache') const { getFnBySourceType } = require('./search-resolvers') diff --git a/packages/ws-server-core/src/options/index.js b/packages/ws-server-core/src/options/index.js index f04878ce..41ff6e21 100644 --- a/packages/ws-server-core/src/options/index.js +++ b/packages/ws-server-core/src/options/index.js @@ -88,10 +88,11 @@ function initWsServerOption(config) { throw new JsonqlValidationError(`initWsServerOption`, SECRET_MISSING_ERR) } } + const { log } = opts // we init an cache object here now for re-use through out the app opts[CACHE_STORE_PROP_KEY] = getCacheStore(opts) - - const { log } = opts + + debug(CACHE_STORE_PROP_KEY, opts[CACHE_STORE_PROP_KEY]) opts[EVENT_EMITTER_PROP_KEY] = new WsServerEventEmitter(log) diff --git a/packages/ws-server-core/src/options/props.js b/packages/ws-server-core/src/options/props.js index 85ac944b..43dbee52 100644 --- a/packages/ws-server-core/src/options/props.js +++ b/packages/ws-server-core/src/options/props.js @@ -35,10 +35,11 @@ const { LOGIN_FN_NAME, LOGOUT_FN_NAME, - CSRF_PROP_KEY + CSRF_PROP_KEY, + JS_WS_NAME, + CSRF_HEADER_KEY } = require('jsonql-constants') -const { SOCKET_IO } = require('./constants') - +// default root folder const dirname = process.cwd() // base options @@ -77,14 +78,14 @@ const wsBaseOptions = { allowOrgin: createConfig(['*'], [ARRAY_TYPE]), serverInitOption: createConfig({}, [OBJECT_TYPE]), // placeholder for now - [CSRF_PROP_KEY]: createConfig('', [STRING_TYPE]), + [CSRF_PROP_KEY]: createConfig(CSRF_HEADER_KEY, [STRING_TYPE]), // if we want to cache the resolver or not enableCacheResolver: createConfig(true, [BOOLEAN_TYPE]) } // we have to create a standlone prop to check if the user pass the socket server config first const socketAppProps = { - [SOCKET_TYPE_PROP_KEY]: createConfig(SOCKET_IO, [STRING_TYPE], { + [SOCKET_TYPE_PROP_KEY]: createConfig(JS_WS_NAME, [STRING_TYPE], { [ALIAS_KEY]: SOCKET_TYPE_SERVER_ALIAS }) } diff --git a/packages/ws-server-core/src/resolver/get-injectors.js b/packages/ws-server-core/src/resolver/get-injectors.js index 7ba3fda6..16d8d15c 100644 --- a/packages/ws-server-core/src/resolver/get-injectors.js +++ b/packages/ws-server-core/src/resolver/get-injectors.js @@ -79,7 +79,7 @@ const injectClient = (resolver, deliverFn, resolverName, ws, userdata, opts) => return opts[INIT_CLIENT_PROP_KEY] .then(clients => injectNodeClient(resolver, clients)) } - + debug('=========================== injectClient ==============================\n', typeof resolver ) return resolver } diff --git a/packages/ws-server-core/src/resolver/resolve-socket-method.js b/packages/ws-server-core/src/resolver/resolve-socket-method.js index eb175731..567bc283 100644 --- a/packages/ws-server-core/src/resolver/resolve-socket-method.js +++ b/packages/ws-server-core/src/resolver/resolve-socket-method.js @@ -35,18 +35,16 @@ const resolveSocketMethod = function( _params.push(key, store) } - const actionFn = Reflect.apply(getCompleteSocketResolver, null, _params) + const constructorFn = Reflect.apply(getCompleteSocketResolver, null, _params) const injectorFns = getInjectors() const params = [ deliverFn, resolverName, ws, userdata, opts ] - + // @BUG the resolverFn return is already a string? + const resolverFn = constructorFn(injectorFns, params) + debug('resolveSocketMethod resolver', typeof resolverFn, resolverFn, args) + return new Promise((resolver, rejecter) => { try { - const resolverFn = actionFn(injectorFns, params) - debug('resolveSocketMethod resolver', typeof resolverFn, resolverFn, args) - - // this is still wrong, why are we not running it throught the validator? - resolver( Reflect.apply(resolverFn, null, args) ) } catch(err) { debug('Error happen here in side the resolveSocketMethod', err) -- Gitee From bd218c6804e1e37f175255b041636f1c4a8361d5 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 12:43:48 +0800 Subject: [PATCH 13/18] Add a placeholder into the getResolver method --- packages/resolver/index.js | 3 +-- packages/resolver/src/handle-auth-methods.js | 23 +++----------------- packages/resolver/src/resolve-methods.js | 20 ++++++++++++++--- 3 files changed, 21 insertions(+), 25 deletions(-) diff --git a/packages/resolver/index.js b/packages/resolver/index.js index ebc005a2..5e1eb29f 100644 --- a/packages/resolver/index.js +++ b/packages/resolver/index.js @@ -41,10 +41,9 @@ const { } = require('./src/cache') const { getCompleteSocketResolver -} = require('./src/combine-resolver') +} = require('./src/get-complete-socket-resolver') -// @TODO use the same for the jsonql-ws-server as well module.exports = { searchResolvers, validateAndCall, diff --git a/packages/resolver/src/handle-auth-methods.js b/packages/resolver/src/handle-auth-methods.js index e110c664..29c54b1b 100644 --- a/packages/resolver/src/handle-auth-methods.js +++ b/packages/resolver/src/handle-auth-methods.js @@ -1,21 +1,5 @@ // Auth methods handler -const fsx = require('fs-extra') -// const { join } = require('path') const { - SOCKET_NAME, - LOGIN_EVENT_NAME, - SWITCH_USER_EVENT_NAME, - LOGOUT_EVENT_NAME, - SA_LOGIN_EVENT_NAME, - CONNECTED_EVENT_NAME, - DISCONNECT_EVENT_NAME, - - LOGIN_FN_NAME_PROP_KEY, - LOGOUT_FN_NAME_PROP_KEY, - INIT_CONNECTION_FN_NAME_PROP_KEY, - DISCONNECT_FN_NAME_PROP_KEY, - SWITCH_USER_FN_NAME_PROP_KEY, - AUTH_TYPE, QUERY_ARG_NAME, UNAUTHORIZED_STATUS @@ -28,10 +12,10 @@ const { UNKNOWN_ERROR } = require('jsonql-errors') const { packResult } = require('jsonql-utils') -const { validateAsync } = require('jsonql-params-validator') +// const { validateAsync } = require('jsonql-params-validator') const { getDebug, ctxErrorHandler, handleOutput } = require('./utils') -const { searchResolvers, getFnBySourceType } = require('./search-resolvers') +const { searchResolvers } = require('./search-resolvers') const { validateAndCall } = require('./validate-and-call') const debug = getDebug('public-method-middleware') @@ -51,6 +35,7 @@ const getLocalValidator = (config, contract) => { // @BUG when this searchResolvers throw error the next call can not use instanceof to check the Error? // @TODO there is no need to pass the type here, it will always be the AUTH_TYPE let validatorFnPath = searchResolvers(validatorHandlerName, AUTH_TYPE, config, contract) + return require(validatorFnPath) } @@ -103,8 +88,6 @@ const handleAuthMethods = async function(ctx, payload, opts, contract) { } - - module.exports = { getLocalValidator, handleAuthMethods diff --git a/packages/resolver/src/resolve-methods.js b/packages/resolver/src/resolve-methods.js index f97e0177..62daf96e 100644 --- a/packages/resolver/src/resolve-methods.js +++ b/packages/resolver/src/resolve-methods.js @@ -37,9 +37,7 @@ const getResolver = (resolverName, type, contract, opts) => { const { sourceType } = contract if (sourceType === MODULE_TYPE) { const pathToResolver = findFromContract(type, resolverName, contract) - debug('call requireEsModule', resolverName, pathToResolver) - return requireEsModule(pathToResolver) } @@ -49,6 +47,21 @@ const getResolver = (resolverName, type, contract, opts) => { } } +/** + * @TODO cache resolver + * @param {string} resolverName name of resolver + * @param {string} type of resolver + * @param {object} contract the contract + * @param {object} opts configuration + * @return {function} resolver + */ +const getCacheResolver = (resolverName, type, contract, opts) => { + // const key = [type, resolverName].join('-') + // next check if there is a store object in the opts + return getResolver(resolverName, type, contract, opts) +} + + /** * A new method breaking out the get resolver and prepare code * then make the original resolveMethod as a koa render handler @@ -61,7 +74,8 @@ const getResolver = (resolverName, type, contract, opts) => { * @return {*} result - process result from resolver */ const executeResolver = (opts, type, resolverName, payload, contract, userdata = false) => { - const fn = getResolver(resolverName, type, contract, opts) + const fn = getCacheResolver(resolverName, type, contract, opts) + const args = extractArgsFromPayload(payload, type) const provider = getNodeClientProvider(opts) // inject the node client if any -- Gitee From d3b77a3a53ac5fc6813a201fb98509d66985b4a5 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 13:17:04 +0800 Subject: [PATCH 14/18] rename the method and test to make more sense --- packages/resolver/package.json | 2 +- packages/resolver/src/cache.js | 9 +++--- .../src/get-complete-socket-resolver.js | 22 +++++--------- .../tests/{combine.test.js => cache.test.js} | 29 ++++++++++++------- 4 files changed, 33 insertions(+), 29 deletions(-) rename packages/resolver/tests/{combine.test.js => cache.test.js} (84%) diff --git a/packages/resolver/package.json b/packages/resolver/package.json index aa5bd9ca..45f8e3a5 100644 --- a/packages/resolver/package.json +++ b/packages/resolver/package.json @@ -10,7 +10,7 @@ "scripts": { "test": "ava", "prepare": "npm run test", - "test:combine": "DEBUG=jsonql-resolver* ava ./tests/combine.test.js", + "test:cache": "DEBUG=jsonql-resolver* ava ./tests/cache.test.js", "test:socket": "DEBUG=jsonql-resolver* ava ./tests/socket.test.js", "test:base": "DEBUG=jsonql* ava ./tests/base.test.js", "test:clients": "DEBUG=jsonql* ava ./tests/clients.test.js", diff --git a/packages/resolver/src/cache.js b/packages/resolver/src/cache.js index e76db89d..9062afd1 100644 --- a/packages/resolver/src/cache.js +++ b/packages/resolver/src/cache.js @@ -19,7 +19,7 @@ const { isCacheObj } = require('@jsonql/security') * @return {*} false when not found */ function getCacheResolver(key, store) { - if (key && isCacheObj(store)) { + if (key && store && isCacheObj(store)) { return store.has(key) ? store.get(key) : false } @@ -37,12 +37,13 @@ function cacheResolver(store) { /** * Although we call it resolverName in the param but this will not just be the resolver name * to avoid name collison - * @param {string} resolverName + * @param {string} key key to id this item + * @param {function} resolver function * @return {function} resolver itself it found */ - return function cacheResolverAction(resolverName, resolver) { + return function cacheResolverAction(key, resolver) { // the set return true on success, then we return the resolver for use next - return store.set(resolverName, resolver) ? resolver : false + return store.set(key, resolver) ? resolver : false } } diff --git a/packages/resolver/src/get-complete-socket-resolver.js b/packages/resolver/src/get-complete-socket-resolver.js index 9414b5b8..7b613231 100644 --- a/packages/resolver/src/get-complete-socket-resolver.js +++ b/packages/resolver/src/get-complete-socket-resolver.js @@ -29,21 +29,15 @@ function getCompleteSocketResolver(resolverName, opts, key = null, store = null) // the contract is within the opts const { contract } = opts - let resolver - // [deliverFn, resolverName, args, opts, ws, userdata] - if (key && store !== null) { - debug('use cache resolver with key', key) + let resolver = getCacheResolver(key, store) + if (resolver !== false) { + debug('return the cache version with key', key, resolver) - resolver = getCacheResolver(key, store) - if (resolver !== false) { - debug('return the cache version with key', key, resolver) - - return resolver - } + return resolver } - - const resolverFn = getResolver(resolverName, SOCKET_NAME, contract, opts) - + + resolver = getResolver(resolverName, SOCKET_NAME, contract, opts) + debug(`return resolver using getResolver`, resolverName, typeof resolver) /** * @param {array} injectors to run through the injection * @param {array<*>} params then we add the resolver at the end to pass through the injectors @@ -52,7 +46,7 @@ function getCompleteSocketResolver(resolverName, opts, key = null, store = null) return function runInjectors(injectors, params) { const executor = Reflect.apply(chainFns, null, injectors) // please note the final injector must return just the resolver - const resolver = Reflect.apply(executor, null, [resolverFn, ...params]) + const resolver = Reflect.apply(executor, null, [resolver, ...params]) if (key && store !== null) { const cacher = cacheResolver(store) diff --git a/packages/resolver/tests/combine.test.js b/packages/resolver/tests/cache.test.js similarity index 84% rename from packages/resolver/tests/combine.test.js rename to packages/resolver/tests/cache.test.js index 3bb7aaf6..de3759d5 100644 --- a/packages/resolver/tests/combine.test.js +++ b/packages/resolver/tests/cache.test.js @@ -24,17 +24,14 @@ test.before(t => { }) test(`Testing the basic cache function first`, t => { - - const check = isCacheObj(t.context.cacheInstance) - - t.true(check) -}) - -test(`Test the nodeCache interface`, t => { + const cache = t.context.cacheInstance const result = cache.set('some-key', 'some-value') t.true(result) + const check = isCacheObj(cache) + + t.true(check) }) test(`Test the getCompleteSocketResolver method`, t => { @@ -51,12 +48,19 @@ test(`Test the getCompleteSocketResolver method`, t => { // part 2 add injector const injectors = [ (fn, key, value) => { + debug('main injector') // debug('pass fn with', fn, key, value) return injectToFn(fn, key, value, true) }, (fn) => { + debug('second injector') // debug('next pass with ', fn) return injectToFn(fn, 'timestamp', ts) + }, + (fn) => { + debug('final injector') + + return injectToFn(fn, 'whatever', 'some property') } ] @@ -74,16 +78,21 @@ test(`Test the getCompleteSocketResolver method`, t => { t.true(typeof resolver === 'function', 'resovler should be a function') + const resolver0 = runInjectorsFn(injectors, [somekey, someval]) // this should return the cache version const resolver1 = getCacheResolver(resolverName, t.context.cacheInstance) - const msg = resolver1('la la la') + const msg0 = resolver0('la la la') - debug('resolver1 result', msg) + debug('resolver0 result', msg) + + const msg1 = resolver1('la la la') + + debug('resolver1 result', msg1) t.is(resolver1.timestamp, ts) t.true(typeof resolver1 === 'function', 'retrieve cache function') - + t.true(typeof resovler0 === 'function') }) test(`testing the getSocketAuthInterceptor methods`, async t => { -- Gitee From 002e2cecd1c0481c1dbbb86b50b7def3668db39c Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 13:22:35 +0800 Subject: [PATCH 15/18] the test passed also so what the f going on on the other side --- packages/resolver/src/cache.js | 6 ++++-- packages/resolver/src/get-complete-socket-resolver.js | 10 +++++----- packages/resolver/tests/cache.test.js | 4 ++-- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/packages/resolver/src/cache.js b/packages/resolver/src/cache.js index 9062afd1..4a33ffad 100644 --- a/packages/resolver/src/cache.js +++ b/packages/resolver/src/cache.js @@ -8,10 +8,9 @@ therefore simply cache this part is not enough 2. We probably have to create a new method that takes in a list of processor (injectors) take the result fn and additional params, run through the injector, then we can cache this resolver - */ const { isCacheObj } = require('@jsonql/security') - +const { JsonqlError } = require('jsonql-errors') /** * get it * @param {*} key @@ -34,6 +33,9 @@ function getCacheResolver(key, store) { * @return {function} method to find the resolver */ function cacheResolver(store) { + if (!isCacheObj(store)) { + throw new JsonqlError(`We expect the cache store to be JsonqlCache but instead we got ${typeof cache}`) + } /** * Although we call it resolverName in the param but this will not just be the resolver name * to avoid name collison diff --git a/packages/resolver/src/get-complete-socket-resolver.js b/packages/resolver/src/get-complete-socket-resolver.js index 7b613231..16861a91 100644 --- a/packages/resolver/src/get-complete-socket-resolver.js +++ b/packages/resolver/src/get-complete-socket-resolver.js @@ -46,15 +46,15 @@ function getCompleteSocketResolver(resolverName, opts, key = null, store = null) return function runInjectors(injectors, params) { const executor = Reflect.apply(chainFns, null, injectors) // please note the final injector must return just the resolver - const resolver = Reflect.apply(executor, null, [resolver, ...params]) + const resolverFn = Reflect.apply(executor, null, [resolver, ...params]) - if (key && store !== null) { - const cacher = cacheResolver(store) + if (key && store) { + const cacherFn = cacheResolver(store) - return cacher(key, resolver) + return cacherFn(key, resolver) } - return resolver + return resolverFn } } diff --git a/packages/resolver/tests/cache.test.js b/packages/resolver/tests/cache.test.js index de3759d5..0dd3db2b 100644 --- a/packages/resolver/tests/cache.test.js +++ b/packages/resolver/tests/cache.test.js @@ -83,7 +83,7 @@ test(`Test the getCompleteSocketResolver method`, t => { const msg0 = resolver0('la la la') - debug('resolver0 result', msg) + debug('resolver0 result', msg0) const msg1 = resolver1('la la la') @@ -92,7 +92,7 @@ test(`Test the getCompleteSocketResolver method`, t => { t.is(resolver1.timestamp, ts) t.true(typeof resolver1 === 'function', 'retrieve cache function') - t.true(typeof resovler0 === 'function') + t.true(typeof resolver0 === 'function') }) test(`testing the getSocketAuthInterceptor methods`, async t => { -- Gitee From fc0ad4cdd0f8316331d54194784cde55822c6eae Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 14:24:08 +0800 Subject: [PATCH 16/18] Now this is finally the correct implementation --- .../src/get-complete-socket-resolver.js | 30 +++++++++++-------- packages/resolver/tests/cache.test.js | 13 +++++--- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/packages/resolver/src/get-complete-socket-resolver.js b/packages/resolver/src/get-complete-socket-resolver.js index 16861a91..c421ef64 100644 --- a/packages/resolver/src/get-complete-socket-resolver.js +++ b/packages/resolver/src/get-complete-socket-resolver.js @@ -7,7 +7,7 @@ const { getCacheResolver, cacheResolver } = require('./cache') const { getResolver } = require('./resolve-methods') const debug = require('debug')('jsonql-resolver:combine-resolver') - +const colors = require('colors/safe') /** * this is a new feature that allow * the framework to pass a list of injectors, and extra props @@ -29,28 +29,34 @@ function getCompleteSocketResolver(resolverName, opts, key = null, store = null) // the contract is within the opts const { contract } = opts - let resolver = getCacheResolver(key, store) - if (resolver !== false) { - debug('return the cache version with key', key, resolver) - - return resolver - } - - resolver = getResolver(resolverName, SOCKET_NAME, contract, opts) - debug(`return resolver using getResolver`, resolverName, typeof resolver) /** * @param {array} injectors to run through the injection * @param {array<*>} params then we add the resolver at the end to pass through the injectors * @return {function} the complete resolver */ - return function runInjectors(injectors, params) { + return function prepareResolver(injectors, params) { + // it should be here otherwise, we call the prepare method will just keep injecting + debug(`start getCompleteSocketResolver`, colors.white.bgRed(key), typeof store) + + let resolver = getCacheResolver(key, store) + if (resolver !== false) { + debug('return the cache version with key', colors.bgMagenta(key), resolver) + + return resolver + } + + resolver = getResolver(resolverName, SOCKET_NAME, contract, opts) + + debug(`return resolver using getResolver`, resolverName, typeof resolver) + const executor = Reflect.apply(chainFns, null, injectors) // please note the final injector must return just the resolver const resolverFn = Reflect.apply(executor, null, [resolver, ...params]) if (key && store) { const cacherFn = cacheResolver(store) - + debug(`caching the resolver using`, key) + return cacherFn(key, resolver) } diff --git a/packages/resolver/tests/cache.test.js b/packages/resolver/tests/cache.test.js index 0dd3db2b..e1e154f8 100644 --- a/packages/resolver/tests/cache.test.js +++ b/packages/resolver/tests/cache.test.js @@ -34,16 +34,21 @@ test(`Testing the basic cache function first`, t => { t.true(check) }) -test(`Test the getCompleteSocketResolver method`, t => { +test.only(`Test the getCompleteSocketResolver method`, t => { const resolverName = 'sendSomething' + const cacheStore = t.context.cacheInstance + const contract = t.context.contract const args = [ resolverName, - {contract: t.context.contract}, - resolverName, - t.context.cacheInstance + { contract }, + resolverName, /// this is the key + cacheStore ] const runInjectorsFn = Reflect.apply(getCompleteSocketResolver, null, args) + + + const ts = Date.now() // part 2 add injector const injectors = [ -- Gitee From 51ca5c80a0abe642376cb51e8872ab8fe8974bff Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 14:31:19 +0800 Subject: [PATCH 17/18] jsonql-resolver 1.2.6 --- packages/resolver/package.json | 2 +- packages/resolver/tests/cache.test.js | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/resolver/package.json b/packages/resolver/package.json index 45f8e3a5..84886ca0 100644 --- a/packages/resolver/package.json +++ b/packages/resolver/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-resolver", - "version": "1.2.5", + "version": "1.2.6", "description": "This is NOT for general use, please do not install it directly. This module is part of the jsonql tools supporting modules.", "main": "index.js", "files": [ diff --git a/packages/resolver/tests/cache.test.js b/packages/resolver/tests/cache.test.js index e1e154f8..d0ad66cd 100644 --- a/packages/resolver/tests/cache.test.js +++ b/packages/resolver/tests/cache.test.js @@ -34,7 +34,7 @@ test(`Testing the basic cache function first`, t => { t.true(check) }) -test.only(`Test the getCompleteSocketResolver method`, t => { +test(`Test the getCompleteSocketResolver method`, t => { const resolverName = 'sendSomething' const cacheStore = t.context.cacheInstance const contract = t.context.contract @@ -47,8 +47,6 @@ test.only(`Test the getCompleteSocketResolver method`, t => { const runInjectorsFn = Reflect.apply(getCompleteSocketResolver, null, args) - - const ts = Date.now() // part 2 add injector const injectors = [ -- Gitee From 38d05bcfca1e326c49f6562a9ab82a0857a0cf23 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 28 Mar 2020 14:56:40 +0800 Subject: [PATCH 18/18] Add back some of the missing prop keys --- packages/constants/README.md | 4 ++ packages/constants/browser.js | 4 ++ packages/constants/constants.json | 4 ++ packages/constants/index.js | 8 ++- packages/constants/main.js | 4 ++ packages/constants/package.json | 2 +- packages/constants/prop.js | 8 ++- packages/ws-server-core/package.json | 2 +- packages/ws-server-core/src/options/props.js | 57 ++++++++++---------- packages/ws-server-core/tests/fn.test.js | 6 ++- 10 files changed, 67 insertions(+), 32 deletions(-) diff --git a/packages/constants/README.md b/packages/constants/README.md index 690c776a..ff4e214e 100755 --- a/packages/constants/README.md +++ b/packages/constants/README.md @@ -154,6 +154,9 @@ Please consult the detail break down below. - WITH_PUBLIC_CONTRACT_PROP_KEY - PUBLIC_KEY_NAME_PROP_KEY - PRIVATE_KEY_NAME_PROP_KEY +- PUBLIC_NAMESPACE_PROP_KEY +- PRIVATE_NAMESPACE_PROP_KEY +- SECRET_PROP_KEY - RSA_MODULE_LEN_PROP_KEY - JSONQL_PATH_PROP_KEY - CONTRACT_KEY_PROP_KEY @@ -173,6 +176,7 @@ Please consult the detail break down below. - CACHE_STORE_PROP_KEY - EVENT_EMITTER_PROP_KEY - SUSPEND_EVENT_PROP_KEY +- ENABLE_CACHE_RESOLVER_PROP_KEY ### SOCKET diff --git a/packages/constants/browser.js b/packages/constants/browser.js index 2891dfe2..7ccec69d 100644 --- a/packages/constants/browser.js +++ b/packages/constants/browser.js @@ -155,6 +155,9 @@ var jsonqlConstants = { "WITH_PUBLIC_CONTRACT_PROP_KEY": "withPublicContract", "PUBLIC_KEY_NAME_PROP_KEY": "publicKeyFileName", "PRIVATE_KEY_NAME_PROP_KEY": "privateKeyFileName", + "PUBLIC_NAMESPACE_PROP_KEY": "publicNamespace", + "PRIVATE_NAMESPACE_PROP_KEY": "privateNamespace", + "SECRET_PROP_KEY": "secret", "RSA_MODULE_LEN_PROP_KEY": "rsaModulusLength", "JSONQL_PATH_PROP_KEY": "jsonqlPath", "CONTRACT_KEY_PROP_KEY": "contractKey", @@ -174,6 +177,7 @@ var jsonqlConstants = { "CACHE_STORE_PROP_KEY": "cacheStore", "EVENT_EMITTER_PROP_KEY": "eventEmitter", "SUSPEND_EVENT_PROP_KEY": "suspendOnStart", + "ENABLE_CACHE_RESOLVER_PROP_KEY": "enableCacheResolver", "SOCKET_PING_EVENT_NAME": "__ping__", "SWITCH_USER_EVENT_NAME": "__switch__", "LOGIN_EVENT_NAME": "__login__", diff --git a/packages/constants/constants.json b/packages/constants/constants.json index cdb9aa67..de326651 100644 --- a/packages/constants/constants.json +++ b/packages/constants/constants.json @@ -155,6 +155,9 @@ "WITH_PUBLIC_CONTRACT_PROP_KEY": "withPublicContract", "PUBLIC_KEY_NAME_PROP_KEY": "publicKeyFileName", "PRIVATE_KEY_NAME_PROP_KEY": "privateKeyFileName", + "PUBLIC_NAMESPACE_PROP_KEY": "publicNamespace", + "PRIVATE_NAMESPACE_PROP_KEY": "privateNamespace", + "SECRET_PROP_KEY": "secret", "RSA_MODULE_LEN_PROP_KEY": "rsaModulusLength", "JSONQL_PATH_PROP_KEY": "jsonqlPath", "CONTRACT_KEY_PROP_KEY": "contractKey", @@ -174,6 +177,7 @@ "CACHE_STORE_PROP_KEY": "cacheStore", "EVENT_EMITTER_PROP_KEY": "eventEmitter", "SUSPEND_EVENT_PROP_KEY": "suspendOnStart", + "ENABLE_CACHE_RESOLVER_PROP_KEY": "enableCacheResolver", "SOCKET_PING_EVENT_NAME": "__ping__", "SWITCH_USER_EVENT_NAME": "__switch__", "LOGIN_EVENT_NAME": "__login__", diff --git a/packages/constants/index.js b/packages/constants/index.js index 5b24c6c5..25496fa4 100644 --- a/packages/constants/index.js +++ b/packages/constants/index.js @@ -216,6 +216,10 @@ export const WITH_PUBLIC_CONTRACT_PROP_KEY = 'withPublicContract' export const PUBLIC_KEY_NAME_PROP_KEY = 'publicKeyFileName' export const PRIVATE_KEY_NAME_PROP_KEY = 'privateKeyFileName' +export const PUBLIC_NAMESPACE_PROP_KEY = 'publicNamespace' +export const PRIVATE_NAMESPACE_PROP_KEY = 'privateNamespace' +export const SECRET_PROP_KEY = 'secret' + export const RSA_MODULE_LEN_PROP_KEY = 'rsaModulusLength' export const JSONQL_PATH_PROP_KEY = 'jsonqlPath' @@ -250,7 +254,9 @@ export const CONNECTED_PROP_KEY = 'connected' export const CACHE_STORE_PROP_KEY = 'cacheStore' export const EVENT_EMITTER_PROP_KEY = 'eventEmitter' // track this key if we want to suspend event on start -export const SUSPEND_EVENT_PROP_KEY = 'suspendOnStart' /* socket.js */ +export const SUSPEND_EVENT_PROP_KEY = 'suspendOnStart' +// if we want to enable caching the resolver or not +export const ENABLE_CACHE_RESOLVER_PROP_KEY = 'enableCacheResolver' /* socket.js */ // the constants file is gettig too large // we need to split up and group the related constant in one file diff --git a/packages/constants/main.js b/packages/constants/main.js index 285b0f5b..53749309 100644 --- a/packages/constants/main.js +++ b/packages/constants/main.js @@ -155,6 +155,9 @@ module.exports = { "WITH_PUBLIC_CONTRACT_PROP_KEY": "withPublicContract", "PUBLIC_KEY_NAME_PROP_KEY": "publicKeyFileName", "PRIVATE_KEY_NAME_PROP_KEY": "privateKeyFileName", + "PUBLIC_NAMESPACE_PROP_KEY": "publicNamespace", + "PRIVATE_NAMESPACE_PROP_KEY": "privateNamespace", + "SECRET_PROP_KEY": "secret", "RSA_MODULE_LEN_PROP_KEY": "rsaModulusLength", "JSONQL_PATH_PROP_KEY": "jsonqlPath", "CONTRACT_KEY_PROP_KEY": "contractKey", @@ -174,6 +177,7 @@ module.exports = { "CACHE_STORE_PROP_KEY": "cacheStore", "EVENT_EMITTER_PROP_KEY": "eventEmitter", "SUSPEND_EVENT_PROP_KEY": "suspendOnStart", + "ENABLE_CACHE_RESOLVER_PROP_KEY": "enableCacheResolver", "SOCKET_PING_EVENT_NAME": "__ping__", "SWITCH_USER_EVENT_NAME": "__switch__", "LOGIN_EVENT_NAME": "__login__", diff --git a/packages/constants/package.json b/packages/constants/package.json index ff1f011e..8d288932 100755 --- a/packages/constants/package.json +++ b/packages/constants/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-constants", - "version": "2.0.14", + "version": "2.0.15", "description": "All the share constants for jsonql modules", "main": "main.js", "module": "index.js", diff --git a/packages/constants/prop.js b/packages/constants/prop.js index 161c5721..14c48407 100644 --- a/packages/constants/prop.js +++ b/packages/constants/prop.js @@ -71,6 +71,10 @@ export const WITH_PUBLIC_CONTRACT_PROP_KEY = 'withPublicContract' export const PUBLIC_KEY_NAME_PROP_KEY = 'publicKeyFileName' export const PRIVATE_KEY_NAME_PROP_KEY = 'privateKeyFileName' +export const PUBLIC_NAMESPACE_PROP_KEY = 'publicNamespace' +export const PRIVATE_NAMESPACE_PROP_KEY = 'privateNamespace' +export const SECRET_PROP_KEY = 'secret' + export const RSA_MODULE_LEN_PROP_KEY = 'rsaModulusLength' export const JSONQL_PATH_PROP_KEY = 'jsonqlPath' @@ -105,4 +109,6 @@ export const CONNECTED_PROP_KEY = 'connected' export const CACHE_STORE_PROP_KEY = 'cacheStore' export const EVENT_EMITTER_PROP_KEY = 'eventEmitter' // track this key if we want to suspend event on start -export const SUSPEND_EVENT_PROP_KEY = 'suspendOnStart' \ No newline at end of file +export const SUSPEND_EVENT_PROP_KEY = 'suspendOnStart' +// if we want to enable caching the resolver or not +export const ENABLE_CACHE_RESOLVER_PROP_KEY = 'enableCacheResolver' \ No newline at end of file diff --git a/packages/ws-server-core/package.json b/packages/ws-server-core/package.json index 447c65a3..90a9954d 100644 --- a/packages/ws-server-core/package.json +++ b/packages/ws-server-core/package.json @@ -36,7 +36,7 @@ "jsonql-constants": "^2.0.14", "jsonql-errors": "^1.2.1", "jsonql-params-validator": "^1.6.2", - "jsonql-resolver": "^1.2.5", + "jsonql-resolver": "^1.2.6", "jsonql-utils": "^1.2.6", "lodash": "^4.17.15" }, diff --git a/packages/ws-server-core/src/options/props.js b/packages/ws-server-core/src/options/props.js index 43dbee52..340bbd10 100644 --- a/packages/ws-server-core/src/options/props.js +++ b/packages/ws-server-core/src/options/props.js @@ -29,7 +29,7 @@ const { SOCKET_TYPE_PROP_KEY, SOCKET_TYPE_SERVER_ALIAS, - INIT_CONNECTION_FN_NAME, + INIT_CONNECTION_FN_NAME_PROP_KEY, DISCONNECT_FN_NAME, SWITCH_USER_FN_NAME, LOGIN_FN_NAME, @@ -44,43 +44,43 @@ const dirname = process.cwd() // base options const wsBaseOptions = { - appDir: createConfig('', [STRING_TYPE]), // just matching the Koa but not in use at the moment + [APP_DIR_PROP_KEY]: createConfig('', [STRING_TYPE]), // just matching the Koa but not in use at the moment // @TODO this will be moving out shortly after the test done // RS256 this will need to figure out how to distribute the key - algorithm: createConfig(HSA_ALGO, [STRING_TYPE]), - authTimeout: createConfig(15000, [NUMBER_TYPE]), + [ALGORITHM_PROP_KEY]: createConfig(HSA_ALGO, [STRING_TYPE]), + [AUTH_TO_PROP_KEY]: createConfig(15000, [NUMBER_TYPE]), // we require the contract already generated and pass here // contract: createConfig({}, [OBJECT_TYPE]), this been causing no end of problem, we don't need it! - enableAuth: createConfig(false, [BOOLEAN_TYPE]), + [ENABLE_AUTH_PROP_KEY]: createConfig(false, [BOOLEAN_TYPE]), // this option now is only for passing the key // this cause a bug because this option is always BOOLEAN and STRING TYPE! - useJwt: createConfig(true, [STRING_TYPE, BOOLEAN_TYPE]), // need to double check this + [USE_JWT_PROP_KEY]: createConfig(true, [STRING_TYPE, BOOLEAN_TYPE]), // need to double check this // update this options to match the jsonql-koa 1.4.10 - resolverDir: createConfig(join(dirname, DEFAULT_RESOLVER_DIR), [STRING_TYPE]), - contractDir: createConfig(join(dirname, DEFAULT_CONTRACT_DIR), [STRING_TYPE]), + [RESOLVER_DIR_PROP_KEY]: createConfig(join(dirname, DEFAULT_RESOLVER_DIR), [STRING_TYPE]), + [CONTRACT_DIR_PROP_KEY]: createConfig(join(dirname, DEFAULT_CONTRACT_DIR), [STRING_TYPE]), // we only want the keys directory then we read it back - keysDir: createConfig(join(dirname, DEFAULT_KEYS_DIR), [STRING_TYPE]), + [KEYS_DIR_PROP_KEY]: createConfig(join(dirname, DEFAULT_KEYS_DIR), [STRING_TYPE]), // @0.6.0 expect this to be the path to the interComEventHandler to handle the INTER_COM_EVENT_NAMES - initConnectionHandlerName: createConfig(INIT_CONNECTION_FN_NAME, [STRING_TYPE]), - loginHandlerName: createConfig(LOGIN_FN_NAME, [STRING_TYPE]), - logoutHandlerName: createConfig(LOGOUT_FN_NAME, [STRING_TYPE]), - disconnectHandlerName: createConfig(DISCONNECT_FN_NAME, [STRING_TYPE]), - switchUserHandlerName: createConfig(SWITCH_USER_FN_NAME, [STRING_TYPE]), + [INIT_CONNECTION_FN_NAME_PROP_KEY]: createConfig('', [STRING_TYPE]), + [LOGIN_FN_NAME_PROP_KEY]: createConfig(LOGIN_FN_NAME, [STRING_TYPE]), + [LOGOUT_FN_NAME_PROP_KEY]: createConfig(LOGOUT_FN_NAME, [STRING_TYPE]), + [DISCONNECT_FN_NAME_PROP_KEY]: createConfig(DISCONNECT_FN_NAME, [STRING_TYPE]), + [SWITCH_USER_FN_NAME_PROP_KEY]: createConfig(SWITCH_USER_FN_NAME, [STRING_TYPE]), // this is for construct the namespace - publicMethodDir: createConfig(PUBLIC_KEY, [STRING_TYPE]), - // just try this with string type first - privateMethodDir: createConfig(PRIVATE_KEY, [STRING_TYPE, BOOLEAN_TYPE]), + // this should be following what is the contract-cli using + [PUBLIC_FN_DIR_PROP_KEY]: createConfig(PUBLIC_KEY, [STRING_TYPE]), + [PRIVATE_FN_DIR_DROP_KEY]: createConfig(PRIVATE_KEY, [STRING_TYPE, BOOLEAN_TYPE]), // this should move to the post check option because it's framework specific - socketIoAuthType: createConfig(false, [STRING_TYPE], { + [SOCKET_IO_AUTH_TYPE_PROP_KEY]: createConfig(false, [STRING_TYPE], { [ENUM_KEY]: [IO_HANDSHAKE_LOGIN, IO_ROUNDTRIP_LOGIN] }), // check the origin if we can - allowOrgin: createConfig(['*'], [ARRAY_TYPE]), - serverInitOption: createConfig({}, [OBJECT_TYPE]), + [ALLOW_ORIGIN_PROP_KEY]: createConfig(['*'], [ARRAY_TYPE]), + [SERVER_INIT_OPT_PROP_KEY]: createConfig({}, [OBJECT_TYPE]), // placeholder for now [CSRF_PROP_KEY]: createConfig(CSRF_HEADER_KEY, [STRING_TYPE]), // if we want to cache the resolver or not - enableCacheResolver: createConfig(true, [BOOLEAN_TYPE]) + [ENABLE_CACHE_RESOLVER_PROP_KEY]: createConfig(true, [BOOLEAN_TYPE]) } // we have to create a standlone prop to check if the user pass the socket server config first @@ -94,12 +94,15 @@ const socketAppProps = { const wsDefaultOptions = Object.assign(wsBaseOptions, socketAppProps) const wsConstProps = { - contract: false, - publicKey: false, - privateKey: false, - secret: false, - publicNamespace: PUBLIC_KEY, - privateNamespace: PRIVATE_KEY + [PUBLIC_KEY_NAME_PROP_KEY]: false, + [PRIVATE_KEY_NAME_PROP_KEY]: false, + [CONTRACT_PROP_KEY]: false, + [SECRET_PROP_KEY]: false, + [PUBLIC_NAMESPACE_PROP_KEY]: PUBLIC_KEY, + [PRIVATE_NAMESPACE_PROP_KEY]: PRIVATE_KEY, + // @TODO they might get replace with the name above + publicKey: false, + privateKey: false } module.exports = { diff --git a/packages/ws-server-core/tests/fn.test.js b/packages/ws-server-core/tests/fn.test.js index c2aefd50..9ccba4d4 100644 --- a/packages/ws-server-core/tests/fn.test.js +++ b/packages/ws-server-core/tests/fn.test.js @@ -45,7 +45,7 @@ test.cb(`Just testing the handleInterCom function interface`, t => { }) -test.only(`test the get-socket-resolver method mainly to look at the cache`, async t => { +test(`test the get-socket-resolver method mainly to look at the cache`, async t => { const opts = { contractDir: join(__dirname, 'fixtures'), resolverDir: join(__dirname, 'fixtures', 'resolvers') @@ -69,12 +69,16 @@ test.only(`test the get-socket-resolver method mainly to look at the cache`, asy const result1 = await Reflect.apply(resolveSocketMethod, null, _params) + debug(result1) + t.truthy(result1) // call it again const result2 = await Reflect.apply(resolveSocketMethod, null, _params) + debug(result2) + // debug(resolver1.toString()) t.truthy(result2) -- Gitee