From e15f9de058a84afda7fe50349c656b588f01b269 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 29 Feb 2020 19:53:22 +0800 Subject: [PATCH 01/15] setup a simple test for the vuex store --- packages/@jsonql/client/package.json | 9 +++++---- packages/@jsonql/client/tests/vuex.test.js | 21 +++++++++++++++++++++ packages/@jsonql/client/vue/index.js | 2 -- packages/@jsonql/client/vue/vuex.js | 17 +++++++++-------- 4 files changed, 35 insertions(+), 14 deletions(-) create mode 100644 packages/@jsonql/client/tests/vuex.test.js diff --git a/packages/@jsonql/client/package.json b/packages/@jsonql/client/package.json index e6a8a92b..143ab380 100644 --- a/packages/@jsonql/client/package.json +++ b/packages/@jsonql/client/package.json @@ -18,6 +18,7 @@ "test": "npm run build && npm run test:browser", "test:basic": "DEBUG=jsonql-client* ava ./tests/basic.test.js", "test:login": "DEBUG=jsonql-client* ava ./tests/login.test.js", + "test:vuex": "ava ./tests/vuex.test.js", "_prepare": "NODE_ENV=production npm run build", "_publish": "npm publish --access public", "test:browser:ws": "npm run build:ws && npm run qunit", @@ -48,7 +49,7 @@ "license": "MIT", "dependencies": { "flyio": "^0.6.14", - "jsonql-client": "^1.5.21" + "jsonql-client": "^1.6.0" }, "optionalDependencies": { "@jsonql/ws": "^1.0.11" @@ -60,11 +61,11 @@ "debug": "^4.1.1", "esm": "^3.2.25", "glob": "^7.1.6", - "koa-favicon": "^2.0.1", + "koa-favicon": "^2.1.0", "nyc": "^15.0.0", "promise-polyfill": "8.1.3", "qunit": "^2.9.3", - "rollup": "^1.31.1", + "rollup": "^1.32.0", "rollup-plugin-alias": "^2.2.0", "rollup-plugin-analyzer": "^3.2.2", "rollup-plugin-async": "^1.2.0", @@ -78,7 +79,7 @@ "rollup-plugin-replace": "^2.2.0", "rollup-plugin-serve": "^1.0.1", "rollup-plugin-terser": "^5.2.0", - "server-io-core": "^1.2.0" + "server-io-core": "^1.3.1" }, "ava": { "files": [ diff --git a/packages/@jsonql/client/tests/vuex.test.js b/packages/@jsonql/client/tests/vuex.test.js new file mode 100644 index 00000000..405c1e6e --- /dev/null +++ b/packages/@jsonql/client/tests/vuex.test.js @@ -0,0 +1,21 @@ +// run a simple test to verify the options are correct or not +const test = require('ava') +const Fly = require("flyio/src/node") +const { join } = require('path') +const fsx = require('fs-extra') +const debug = require('debug')('jsonql-client:test:vuex') +const contract = fsx.readJsonSync(join(__dirname, 'fixtures', 'contract', 'public-contract.json')) +const config = { + contract, + hostname: 'http://localhost:3456' // just a dummy one +} +const { getJsonqlVuexModule } = require('../vue') + +test(`It should able to generate a Vuex store with the flat clients`, t => { + + const store = getJsonqlVuexModule(Fly, config) + + debug(store) + + t.truthy(store) +}) diff --git a/packages/@jsonql/client/vue/index.js b/packages/@jsonql/client/vue/index.js index 34e40d81..63a6b734 100644 --- a/packages/@jsonql/client/vue/index.js +++ b/packages/@jsonql/client/vue/index.js @@ -1,8 +1,6 @@ // jsonql client for Vue and Vuex (TBC) how to do it import { getJsonqlVuexModule } from './vuex' - - export { getJsonqlVuexModule } diff --git a/packages/@jsonql/client/vue/vuex.js b/packages/@jsonql/client/vue/vuex.js index 0bac69c7..4b1e7fa5 100644 --- a/packages/@jsonql/client/vue/vuex.js +++ b/packages/@jsonql/client/vue/vuex.js @@ -11,24 +11,25 @@ const ucword = str => ( /** * create actions on the fly - * @param {object} contract the contract object * @param {object} jsonqlClient static version - * @param {boolean} [prefix=true] add prefix or not + * @param {object} config the configuration object * @return {array} actions, names */ -function getActions(contract, jsonqlClient, prefix = false) { +function getActions(jsonqlClient, config) { + const { prefix, contract, namespaced } = config // could be undefined but we want false boolean const availableTypes = ['query', 'mutation', 'auth'] let actions = {} let names = {} for (let name in contract) { if (availableTypes.indexOf(name) > -1) { for (let resolverName in contract[name]) { - let actionName = prefix === false ? resolverName : name + ucword(resolverName) + let actionName = prefix === true ? name + ucword(resolverName) : resolverName // keep the name for export names[actionName] = null + let clientInstance = namespaced === true ? jsonqlClient[name] : jsonqlClient // define actions actions[actionName] = (ctx, ...args) => { - return Reflect.apply(jsonqlClient[name], jsonqlClient, [resolverName].concat(args)) + return Reflect.apply(clientInstance[resolverName], jsonqlClient, args) .then(result => { ctx.commit('addToResult', {name: actionName, result}) return result @@ -51,9 +52,8 @@ function getActions(contract, jsonqlClient, prefix = false) { * @return {object} the Vuex store object */ function getJsonqlVuexModule(Fly, config) { - const { prefix, contract } = config // could be undefined but we want false boolean const jsonqlClient = jsonqlStaticClient(Fly, config) - const [ actions, names ] = getActions(contract, jsonqlClient, prefix) + const [ actions, names ] = getActions(jsonqlClient, config) // just create the structure on the fly return { namespaced: true, @@ -69,7 +69,8 @@ function getJsonqlVuexModule(Fly, config) { state.error[name] = error } }, - // because jsonql are all async call, everything will be create as action + // because jsonql are all async call, + // every resolver will be warp in as action actions: actions, getters: { getJsonqlResult: (state) => (name) => { -- Gitee From 04149d914d440426d174901b7b3d38dd82abe783 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 29 Feb 2020 20:22:14 +0800 Subject: [PATCH 02/15] test passed --- packages/@jsonql/client/package.json | 2 +- packages/@jsonql/client/tests/vuex.test.js | 4 ++-- packages/@jsonql/client/vue/vuex.js | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/@jsonql/client/package.json b/packages/@jsonql/client/package.json index 143ab380..889ea90e 100644 --- a/packages/@jsonql/client/package.json +++ b/packages/@jsonql/client/package.json @@ -18,7 +18,7 @@ "test": "npm run build && npm run test:browser", "test:basic": "DEBUG=jsonql-client* ava ./tests/basic.test.js", "test:login": "DEBUG=jsonql-client* ava ./tests/login.test.js", - "test:vuex": "ava ./tests/vuex.test.js", + "test:vuex": "DEBUG=jsonql-client* ava ./tests/vuex.test.js", "_prepare": "NODE_ENV=production npm run build", "_publish": "npm publish --access public", "test:browser:ws": "npm run build:ws && npm run qunit", diff --git a/packages/@jsonql/client/tests/vuex.test.js b/packages/@jsonql/client/tests/vuex.test.js index 405c1e6e..2c9692f2 100644 --- a/packages/@jsonql/client/tests/vuex.test.js +++ b/packages/@jsonql/client/tests/vuex.test.js @@ -9,11 +9,11 @@ const config = { contract, hostname: 'http://localhost:3456' // just a dummy one } -const { getJsonqlVuexModule } = require('../vue') +const { getJsonqlVuexModule, getActions } = require('../vue/vuex') test(`It should able to generate a Vuex store with the flat clients`, t => { - const store = getJsonqlVuexModule(Fly, config) + const store = getActions({'query': {}, 'mutation': {}, 'auth': {}}, config) debug(store) diff --git a/packages/@jsonql/client/vue/vuex.js b/packages/@jsonql/client/vue/vuex.js index 4b1e7fa5..6efb315c 100644 --- a/packages/@jsonql/client/vue/vuex.js +++ b/packages/@jsonql/client/vue/vuex.js @@ -80,4 +80,4 @@ function getJsonqlVuexModule(Fly, config) { } } -export { getJsonqlVuexModule } +export { getJsonqlVuexModule, getActions } -- Gitee From 04438b94138d453de64a5e8d9b0e84e0bbb31020 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 29 Feb 2020 21:19:15 +0800 Subject: [PATCH 03/15] setup some of the new options and ready for 1.6.0 release --- packages/koa/package.json | 2 +- packages/koa/src/options/options.js | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/koa/package.json b/packages/koa/package.json index 6c1f4359..cd73b6c2 100644 --- a/packages/koa/package.json +++ b/packages/koa/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-koa", - "version": "1.5.7", + "version": "1.6.0", "description": "jsonql Koa middleware", "main": "main.js", "module": "index.js", diff --git a/packages/koa/src/options/options.js b/packages/koa/src/options/options.js index 99546645..828be098 100644 --- a/packages/koa/src/options/options.js +++ b/packages/koa/src/options/options.js @@ -32,6 +32,7 @@ import { createConfig, constructConfig } from 'jsonql-params-validator' +const DEFAULT_APP_DIR = 'app' // const NodeCache from 'node-cache'); // const mcache = new NodeCache; // @BUG when we deploy it in docker, or using systemd the workingDirectory affect the @@ -54,6 +55,7 @@ const constProps = { const appProps = { name: createConfig('jsonql-koa', [STRING_TYPE]), // this is for ID which one is which when use as ms expired: createConfig(0, [NUMBER_TYPE]), + appDir: createConfig(join(dirname, DEFAULT_APP_DIR), [STRING_TYPE]), // allow user to change their auth type methods name loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]), logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]), -- Gitee From 617b36bdbc0179656233aa1a7f7ae581c7924791 Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 2 Mar 2020 10:34:52 +0800 Subject: [PATCH 04/15] commit the previous changes before continue with updating node-client --- packages/@jsonql/koa/src/jsonql-koa-server.js | 2 +- packages/utils/src/obj-define-props.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/@jsonql/koa/src/jsonql-koa-server.js b/packages/@jsonql/koa/src/jsonql-koa-server.js index 0a9b0679..ed4dec40 100644 --- a/packages/@jsonql/koa/src/jsonql-koa-server.js +++ b/packages/@jsonql/koa/src/jsonql-koa-server.js @@ -28,7 +28,7 @@ class JsonqlKoaServer { // start the server start(port) { if (!this.started) { - console.info(`Server version: ${version} start on ${port || this.opts.port}`) + console.info(`[jsonql Koa server] version: ${version} start on ${port || this.opts.port}`) this.server.listen(port || this.opts.port) this.started = true } diff --git a/packages/utils/src/obj-define-props.js b/packages/utils/src/obj-define-props.js index 993f7ee9..98d76e63 100644 --- a/packages/utils/src/obj-define-props.js +++ b/packages/utils/src/obj-define-props.js @@ -45,7 +45,7 @@ export function injectToFn(resolver, name, data, overwrite = false) { // console.info(`NOT INJECTED`) return resolver } - /* this will throw error! + /* this will throw error! @TODO how to remove props? if (overwrite === true && check !== undefined) { delete resolver[name] // delete this property } -- Gitee From d9a3eb272fe0fe05aa6480ecfb5148288a1e60e9 Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 2 Mar 2020 10:41:41 +0800 Subject: [PATCH 05/15] Mark all the things we need to do with the @jsonql/cli --- packages/@jsonql/cli/README.md | 28 ++++++++++++++++++++++ packages/@jsonql/cli/client.js | 1 + packages/@jsonql/cli/index.js | 1 + packages/@jsonql/cli/package.json | 12 ++++++---- packages/@jsonql/cli/{ => src}/init-dir.js | 0 packages/node-client/package.json | 1 + 6 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 packages/@jsonql/cli/README.md create mode 100644 packages/@jsonql/cli/client.js create mode 100644 packages/@jsonql/cli/index.js rename packages/@jsonql/cli/{ => src}/init-dir.js (100%) diff --git a/packages/@jsonql/cli/README.md b/packages/@jsonql/cli/README.md new file mode 100644 index 00000000..001c4de0 --- /dev/null +++ b/packages/@jsonql/cli/README.md @@ -0,0 +1,28 @@ +# @jsonql/cli + +This is an interactive command line client to setup project, +also comes with a command line interface to access a jsonql server. + +## Installation + +You **really should** install this globally: + +```sh +$ npm install --global @jsonql/cli +``` + +## jsonql + +This is the setup tool + +```sh +$ jsonql +``` + +## jsonql-cli + +This is the command line client + +```sh +$ jsonql-cli http://host-to-your-jsonql +``` diff --git a/packages/@jsonql/cli/client.js b/packages/@jsonql/cli/client.js new file mode 100644 index 00000000..c86918e5 --- /dev/null +++ b/packages/@jsonql/cli/client.js @@ -0,0 +1 @@ +#!/bin/node diff --git a/packages/@jsonql/cli/index.js b/packages/@jsonql/cli/index.js new file mode 100644 index 00000000..c86918e5 --- /dev/null +++ b/packages/@jsonql/cli/index.js @@ -0,0 +1 @@ +#!/bin/node diff --git a/packages/@jsonql/cli/package.json b/packages/@jsonql/cli/package.json index f0f1f261..eabe8c15 100644 --- a/packages/@jsonql/cli/package.json +++ b/packages/@jsonql/cli/package.json @@ -1,7 +1,7 @@ { "name": "@jsonql/cli", "version": "0.1.0", - "description": "Interactive cli program to setup your jsonql dev environment", + "description": "Interactive cli program to setup your jsonql dev environment, and a command line client", "main": "index.js", "scripts": { "test": "ava" @@ -12,7 +12,11 @@ "interactive", "shell" ], - "homepage": "jsonql.org", - "author": "Joel Chu ", - "license": "ISC" + "homepage": "https://jsonql.org", + "author": "Joel Chu ", + "license": "UNLICENSED", + "bin": { + "jsonql": "./index.js", + "jsonql-cli": "./client.js" + } } diff --git a/packages/@jsonql/cli/init-dir.js b/packages/@jsonql/cli/src/init-dir.js similarity index 100% rename from packages/@jsonql/cli/init-dir.js rename to packages/@jsonql/cli/src/init-dir.js diff --git a/packages/node-client/package.json b/packages/node-client/package.json index 3edf2cad..25383e72 100755 --- a/packages/node-client/package.json +++ b/packages/node-client/package.json @@ -41,6 +41,7 @@ ], "license": "MIT", "dependencies": { + "@to1source/request": "^0.9.1", "debug": "^4.1.1", "flyio": "^0.6.14", "fs-extra": "^8.1.0", -- Gitee From a2312300a4180655874c20b931ab17b9a5b97168 Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 2 Mar 2020 11:23:34 +0800 Subject: [PATCH 06/15] start replacing the request npm --- packages/node-client/package.json | 4 ++-- packages/node-client/src/base/request-client.js | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/packages/node-client/package.json b/packages/node-client/package.json index 25383e72..51d7d299 100755 --- a/packages/node-client/package.json +++ b/packages/node-client/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-node-client", - "version": "1.2.12", + "version": "1.3.0", "description": "jsonql node.js client with ws clients", "main": "index.js", "scripts": { @@ -41,7 +41,7 @@ ], "license": "MIT", "dependencies": { - "@to1source/request": "^0.9.1", + "@to1source/request": "^0.9.2", "debug": "^4.1.1", "flyio": "^0.6.14", "fs-extra": "^8.1.0", diff --git a/packages/node-client/src/base/request-client.js b/packages/node-client/src/base/request-client.js index 9c373a35..6e4a13de 100755 --- a/packages/node-client/src/base/request-client.js +++ b/packages/node-client/src/base/request-client.js @@ -2,7 +2,9 @@ * @1.3.0 replace request with flyio because request is deprecated */ // const Fly = require("flyio/src/node") -const request = require('request') // too much work for now +// const request = require('request') // too much work for now +const request = require('@to1source/request') +const querystring = require('querystring') const fsx = require('fs-extra') const { createQuery, createMutation } = require('jsonql-utils') const { clientErrorsHandler } = require('jsonql-errors') @@ -21,7 +23,9 @@ class JsonqlRequestClient extends JsonqlClient { // this.request = new Fly() } - // just a wrapper + /** + * just a wrapper + */ getContract() { return this.__readContract().then(result => { if (typeof result === 'string') { @@ -39,6 +43,13 @@ class JsonqlRequestClient extends JsonqlClient { */ __requestWrapper(method, payload, headers) { debug('sending payload', display(payload,1)) + const url = [this.__url__, querystring.stringify(this.__cacheBurst())].join('?') + + return request.jsonql(url, payload, { method }) + .then(result => { + return this.__interceptor(payload, result) + }) + /* return new Promise((resolver, rejecter) => { try { request({ @@ -63,6 +74,7 @@ class JsonqlRequestClient extends JsonqlClient { rejecter(e) } }) + */ } /** -- Gitee From d6a03e026c6df8a467362b344b6f22264e0db8f2 Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 2 Mar 2020 12:19:20 +0800 Subject: [PATCH 07/15] Apply the namespaced option --- .../node-client/src/base/request-client.js | 6 +++--- .../node-client/src/create-socket-client.js | 2 +- packages/node-client/src/generator.js | 20 +++++++++++-------- packages/node-client/src/options/index.js | 3 ++- 4 files changed, 18 insertions(+), 13 deletions(-) diff --git a/packages/node-client/src/base/request-client.js b/packages/node-client/src/base/request-client.js index 6e4a13de..f78a46e5 100755 --- a/packages/node-client/src/base/request-client.js +++ b/packages/node-client/src/base/request-client.js @@ -3,7 +3,7 @@ */ // const Fly = require("flyio/src/node") // const request = require('request') // too much work for now -const request = require('@to1source/request') +const request = require('@to1source/request/jsonql') const querystring = require('querystring') const fsx = require('fs-extra') const { createQuery, createMutation } = require('jsonql-utils') @@ -44,9 +44,9 @@ class JsonqlRequestClient extends JsonqlClient { __requestWrapper(method, payload, headers) { debug('sending payload', display(payload,1)) const url = [this.__url__, querystring.stringify(this.__cacheBurst())].join('?') - + return request.jsonql(url, payload, { method }) - .then(result => { + .then(({result}) => { return this.__interceptor(payload, result) }) /* diff --git a/packages/node-client/src/create-socket-client.js b/packages/node-client/src/create-socket-client.js index eecc9bc5..9bdcc804 100644 --- a/packages/node-client/src/create-socket-client.js +++ b/packages/node-client/src/create-socket-client.js @@ -14,7 +14,7 @@ function getSocketClient(serverType) { switch (serverType) { case JS_WS_NAME: const jsonqlWsClient = require('@jsonql/ws/node') - return jsonqlWsClient; + return jsonqlWsClient case JS_WS_SOCKET_IO_NAME: case JS_PRIMUS_NAME: diff --git a/packages/node-client/src/generator.js b/packages/node-client/src/generator.js index 8e1f0c40..0de9f1d8 100755 --- a/packages/node-client/src/generator.js +++ b/packages/node-client/src/generator.js @@ -46,13 +46,14 @@ function authMethodGenerator(jsonqlInstance, name, opts, contract) { * @return {object} constructed functions call */ function generator(jsonqlInstance, config, contract) { - let obj = {query: {}, mutation: {}, auth: {}}; + const { namespaced } = config + let obj = namespaced === true ? {query: {}, mutation: {}, auth: {}} : {} // process the query first for (let queryFn in contract.query) { // to keep it clean we use a param to id the auth method // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn; // generate the query method - obj.query[queryFn] = (...args) => { + (namespaced === true ? obj.query[queryFn] : obj[queryFn]) = (...args) => { const params = contract.query[queryFn].params; const _args = params.map((param, i) => args[i]) debug('query', queryFn, _args) @@ -71,7 +72,7 @@ function generator(jsonqlInstance, config, contract) { // there is only the payload, and conditions parameters // plus a header at the end for (let mutationFn in contract.mutation) { - obj.mutation[mutationFn] = (payload, conditions) => { + (namespaced === true ? obj.mutation[mutationFn] : obj[mutationFn]) = (payload, conditions) => { const params = contract.mutation[mutationFn].params; const header = {}; return validateAsync([payload, conditions], params) @@ -111,16 +112,19 @@ function generator(jsonqlInstance, config, contract) { // we have to make this into a function if I want to // need to create a getter method for it otherwise // it's straight through pass to the instance property - obj.userdata = () => jsonqlInstance.userdata; + obj.userdata = () => jsonqlInstance.userdata + } + // @TODO if namespaced = false then we flatten the 3 together + if (namspaced === false) { + // create an alias to the helloWorld make it easier for testing + obj.helloWorld = obj.query.helloWorld } - // create an alias to the helloWorld make it easier for testing - obj.helloWorld = obj.query.helloWorld; // the eventEmitter getter - it should not be inside the auth! obj.eventEmitter = () => jsonqlInstance.eventEmitter // store this once again and export it - obj.getJsonqlInstance = () => jsonqlInstance; + obj.getJsonqlInstance = () => jsonqlInstance // output - return obj; + return obj } // export module.exports = { diff --git a/packages/node-client/src/options/index.js b/packages/node-client/src/options/index.js index 71889f1f..41f61fad 100755 --- a/packages/node-client/src/options/index.js +++ b/packages/node-client/src/options/index.js @@ -50,7 +50,8 @@ const appProps = { hostname: constructConfig('', STRING_TYPE), // required the hostname jsonqlPath: constructConfig(JSONQL_PATH, STRING_TYPE), // The path on the server - + // matching the browser client version + namespaced: createConfig(false, [BOOLEAN_TYPE]), useJwt: createConfig(true, [BOOLEAN_TYPE]), loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]), -- Gitee From 35bf25a14bc1081dcbc4130a2fcf11affc8bbecb Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 2 Mar 2020 12:25:31 +0800 Subject: [PATCH 08/15] Fix the namespaced option --- packages/node-client/src/generator.js | 20 ++++++++++++++------ packages/node-client/tests/main.test.js | 8 ++++---- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/packages/node-client/src/generator.js b/packages/node-client/src/generator.js index 0de9f1d8..0121db21 100755 --- a/packages/node-client/src/generator.js +++ b/packages/node-client/src/generator.js @@ -47,14 +47,16 @@ function authMethodGenerator(jsonqlInstance, name, opts, contract) { */ function generator(jsonqlInstance, config, contract) { const { namespaced } = config - let obj = namespaced === true ? {query: {}, mutation: {}, auth: {}} : {} + let queryObj = {} + let mutationObj = {} + let obj = {} // process the query first for (let queryFn in contract.query) { // to keep it clean we use a param to id the auth method // const fn = (_contract.query[queryFn].auth === true) ? 'auth' : queryFn; // generate the query method - (namespaced === true ? obj.query[queryFn] : obj[queryFn]) = (...args) => { - const params = contract.query[queryFn].params; + queryObj[queryFn] = (...args) => { + const params = contract.query[queryFn].params const _args = params.map((param, i) => args[i]) debug('query', queryFn, _args) // the +1 parameter is the extra headers we want to pass @@ -72,7 +74,7 @@ function generator(jsonqlInstance, config, contract) { // there is only the payload, and conditions parameters // plus a header at the end for (let mutationFn in contract.mutation) { - (namespaced === true ? obj.mutation[mutationFn] : obj[mutationFn]) = (payload, conditions) => { + mutationObj[mutationFn] = (payload, conditions) => { const params = contract.mutation[mutationFn].params; const header = {}; return validateAsync([payload, conditions], params) @@ -114,8 +116,14 @@ function generator(jsonqlInstance, config, contract) { // it's straight through pass to the instance property obj.userdata = () => jsonqlInstance.userdata } - // @TODO if namespaced = false then we flatten the 3 together - if (namspaced === false) { + if (namespaced === true) { + obj.query = queryObj + obj.mutation = mutationObj + } else { + obj = Object.assign(obj, queryObj, mutationObj) + } + + if (namespaced === true) { // create an alias to the helloWorld make it easier for testing obj.helloWorld = obj.query.helloWorld } diff --git a/packages/node-client/tests/main.test.js b/packages/node-client/tests/main.test.js index 749b778e..0494adcc 100755 --- a/packages/node-client/tests/main.test.js +++ b/packages/node-client/tests/main.test.js @@ -9,7 +9,7 @@ const debug = require('debug')('jsonql-node-client:test:main') test.before(async t => { // create server const { stop } = await server() - t.context.stop = stop; + t.context.stop = stop // create client t.context.client = await nodeClient({ @@ -29,15 +29,15 @@ test(`Just to cause the jsonql-koa to run`, t => { }) */ -test('Should able to say Hello world using the shorthand version!' , async t => { +test.only('Should able to say Hello world using the shorthand version!' , async t => { // debug(t.context.client); const result = await t.context.client.helloWorld() t.is('Hello world!', result) }) -test(`It should able to access the mutation call`, async t => { +test(`It should able to access the mutation call using the new non-namspaced option`, async t => { - const result = await t.context.client.mutation.sendUser({name: 'Joel'}, {id: 1}) + const result = await t.context.client.sendUser({name: 'Joel'}, {id: 1}) t.truthy(result.timestamp) }) -- Gitee From d9eb3a1cd5bf80d57a3e80ee4d826591cb2789cd Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 2 Mar 2020 12:33:17 +0800 Subject: [PATCH 09/15] Fix the namespaced option --- .../node-client/src/base/jsonql-base-cls.js | 35 ++++++------------- .../node-client/src/base/request-client.js | 14 ++++---- 2 files changed, 18 insertions(+), 31 deletions(-) diff --git a/packages/node-client/src/base/jsonql-base-cls.js b/packages/node-client/src/base/jsonql-base-cls.js index c01f5764..83fdbc18 100755 --- a/packages/node-client/src/base/jsonql-base-cls.js +++ b/packages/node-client/src/base/jsonql-base-cls.js @@ -36,9 +36,9 @@ class JsonqlClient extends JsonqlCacheClass { get userdata() { if (this.opts.useJwt) { let token = this.__getAuthToken() - return token ? decodeToken(token) : false; + return token ? decodeToken(token) : false } - return false; + return false } /** @@ -59,26 +59,10 @@ class JsonqlClient extends JsonqlCacheClass { * @param {mixed} body from server with the data key */ __interceptor(payload, body) { - const result = typeof body === 'string' ? JSON.parse(body) : body; - const resolverName = Object.keys(payload)[0]; - // this could create a potential bug when some idiot name their - // resolver similar to their auth methods! - /* - const { loginHandlerName, logoutHandlerName } = this.opts; - switch (true) { - case loginHandlerName === resolverName: - debug(`intercept the ${loginHandlerName}`) - if (result.data) { - this.token = result.data; - } - break; - case logoutHandlerName === resolverName: - debug(`intercept the ${logoutHandlerName}`) - this.logout() - break; - } - */ - return result; + const result = typeof body === 'string' ? JSON.parse(body) : body + const resolverName = Object.keys(payload)[0] + + return result } /** @@ -90,16 +74,17 @@ class JsonqlClient extends JsonqlCacheClass { } /** + * @TODO need to change to use with our own new request method * @param {object} header to set * @return {object} combined header * @private */ __createHeaders(header = {}) { const authHeader = this.__getAuthHeader() - let _header = merge({}, this.baseHeader, header, authHeader) + let _header = merge({}, header, authHeader) debug('sending header', _header) - return _header; + return _header } /** @@ -178,4 +163,4 @@ class JsonqlClient extends JsonqlCacheClass { } // export -module.exports = JsonqlClient; +module.exports = JsonqlClient diff --git a/packages/node-client/src/base/request-client.js b/packages/node-client/src/base/request-client.js index f78a46e5..a1922a78 100755 --- a/packages/node-client/src/base/request-client.js +++ b/packages/node-client/src/base/request-client.js @@ -1,15 +1,16 @@ /** * @1.3.0 replace request with flyio because request is deprecated */ -// const Fly = require("flyio/src/node") -// const request = require('request') // too much work for now +// const request = require('request') // @REMOVE const request = require('@to1source/request/jsonql') const querystring = require('querystring') const fsx = require('fs-extra') const { createQuery, createMutation } = require('jsonql-utils') const { clientErrorsHandler } = require('jsonql-errors') + const { API_REQUEST_METHODS } = require('jsonql-constants') -const [ POST, PUT ] = API_REQUEST_METHODS; +const [ POST, PUT ] = API_REQUEST_METHODS + const { display, getDebug, resultHandler } = require('../utils') const JsonqlClient = require('./jsonql-base-cls') @@ -20,7 +21,6 @@ class JsonqlRequestClient extends JsonqlClient { constructor(config = {}) { super(config) - // this.request = new Fly() } /** @@ -31,7 +31,7 @@ class JsonqlRequestClient extends JsonqlClient { if (typeof result === 'string') { return fsx.readJsonSync(result) } - return result; + return result }) } @@ -43,10 +43,12 @@ class JsonqlRequestClient extends JsonqlClient { */ __requestWrapper(method, payload, headers) { debug('sending payload', display(payload,1)) + const url = [this.__url__, querystring.stringify(this.__cacheBurst())].join('?') return request.jsonql(url, payload, { method }) .then(({result}) => { + debug('got result from request', result) return this.__interceptor(payload, result) }) /* @@ -109,4 +111,4 @@ class JsonqlRequestClient extends JsonqlClient { } } -module.exports = JsonqlRequestClient; +module.exports = JsonqlRequestClient -- Gitee From 2f16fa66ecbb3a0232b1c86bcb1b15a9d7fd355e Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 2 Mar 2020 12:40:18 +0800 Subject: [PATCH 10/15] A strange bug happens somewhere but could not pin point it at the moment --- packages/node-client/src/base/request-client.js | 4 ++++ packages/node-client/src/create-socket-client.js | 6 +++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/node-client/src/base/request-client.js b/packages/node-client/src/base/request-client.js index a1922a78..8ba3ce71 100755 --- a/packages/node-client/src/base/request-client.js +++ b/packages/node-client/src/base/request-client.js @@ -51,6 +51,10 @@ class JsonqlRequestClient extends JsonqlClient { debug('got result from request', result) return this.__interceptor(payload, result) }) + .catch(err => { + debug('Error happens here in request', err) + throw new Error(err) + }) /* return new Promise((resolver, rejecter) => { try { diff --git a/packages/node-client/src/create-socket-client.js b/packages/node-client/src/create-socket-client.js index 9bdcc804..0d622897 100644 --- a/packages/node-client/src/create-socket-client.js +++ b/packages/node-client/src/create-socket-client.js @@ -36,10 +36,10 @@ function getSocketClient(serverType) { */ function createSocketClient(client, config, contract) { try { - const { serverType } = config; - debug('config', config[CHECKED_KEY], config) - debug('serverType', serverType) + const { serverType } = config if (serverType) { + debug('config', config[CHECKED_KEY], config) + debug('serverType', serverType) let constProp = { // also need to pass the contract contract, -- Gitee From 38b718dd1f67b4c6b1e5c4137b88bceeae3544bb Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 2 Mar 2020 13:17:10 +0800 Subject: [PATCH 11/15] Unable to see the debug output wtf --- packages/node-client/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/node-client/package.json b/packages/node-client/package.json index 51d7d299..3c12e8d0 100755 --- a/packages/node-client/package.json +++ b/packages/node-client/package.json @@ -41,7 +41,7 @@ ], "license": "MIT", "dependencies": { - "@to1source/request": "^0.9.2", + "@to1source/request": "^0.9.3", "debug": "^4.1.1", "flyio": "^0.6.14", "fs-extra": "^8.1.0", -- Gitee From 105270007b58d364090622a85c4b6a9cd9f270c9 Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 2 Mar 2020 13:19:53 +0800 Subject: [PATCH 12/15] add a server for debug to see what is going on --- packages/node-client/package.json | 3 ++- packages/node-client/tests/fixtures/server-for-debug.js | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 packages/node-client/tests/fixtures/server-for-debug.js diff --git a/packages/node-client/package.json b/packages/node-client/package.json index 3c12e8d0..f92b65aa 100755 --- a/packages/node-client/package.json +++ b/packages/node-client/package.json @@ -14,7 +14,8 @@ "test:config": "DEBUG=jsonql-node-client* ava tests/config.test.js", "test:jwt": "DEBUG=jsonql-node-client*,jsonql-contract* ava tests/jwt.test.js", "test:socket": "DEBUG=jsonql-* ava --verbose tests/socket.test.js", - "test:ms": "DEBUG=jsonql-node-client:main,jsonql-koa:process-contract ava --verbose tests/ms.test.js" + "test:ms": "DEBUG=jsonql-node-client:main,jsonql-koa:process-contract ava --verbose tests/ms.test.js", + "start:debug": "node ./tests/fixtures/server-for-debug" }, "homepage": "jsonql.org", "repository": { diff --git a/packages/node-client/tests/fixtures/server-for-debug.js b/packages/node-client/tests/fixtures/server-for-debug.js new file mode 100644 index 00000000..5dcaf4ad --- /dev/null +++ b/packages/node-client/tests/fixtures/server-for-debug.js @@ -0,0 +1,3 @@ +const server = require('./server') + +server() -- Gitee From 0e7b5f5e7e8ce8d56ecda666685ce2f9ee070e69 Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 2 Mar 2020 14:23:16 +0800 Subject: [PATCH 13/15] update all the tests --- packages/node-client/package.json | 10 +++++----- packages/node-client/tests/auth.test.js | 1 + packages/node-client/tests/jwt.test.js | 1 + packages/node-client/tests/main.test.js | 2 +- packages/node-client/tests/ms.test.js | 2 ++ packages/node-client/tests/socket.test.js | 2 +- packages/node-client/tests/validation.test.js | 14 +++++++------- 7 files changed, 18 insertions(+), 14 deletions(-) diff --git a/packages/node-client/package.json b/packages/node-client/package.json index f92b65aa..9c6426f6 100755 --- a/packages/node-client/package.json +++ b/packages/node-client/package.json @@ -15,7 +15,7 @@ "test:jwt": "DEBUG=jsonql-node-client*,jsonql-contract* ava tests/jwt.test.js", "test:socket": "DEBUG=jsonql-* ava --verbose tests/socket.test.js", "test:ms": "DEBUG=jsonql-node-client:main,jsonql-koa:process-contract ava --verbose tests/ms.test.js", - "start:debug": "node ./tests/fixtures/server-for-debug" + "start:debug": "DEBUG=jsonql-* node ./tests/fixtures/server-for-debug" }, "homepage": "jsonql.org", "repository": { @@ -42,7 +42,7 @@ ], "license": "MIT", "dependencies": { - "@to1source/request": "^0.9.3", + "@to1source/request": "^0.9.4", "debug": "^4.1.1", "flyio": "^0.6.14", "fs-extra": "^8.1.0", @@ -59,12 +59,12 @@ "@jsonql/ws": "^1.0.11" }, "devDependencies": { - "ava": "^3.3.0", + "ava": "^3.5.0", "jsonql-contract": "^1.8.7", - "jsonql-koa": "^1.5.6", + "jsonql-koa": "^1.5.7", "jsonql-ws-server": "^1.5.3", "nyc": "^15.0.0", - "server-io-core": "^1.2.0", + "server-io-core": "^1.3.1", "superkoa": "^1.0.3" }, "ava": { diff --git a/packages/node-client/tests/auth.test.js b/packages/node-client/tests/auth.test.js index 74fec7b8..afe235c7 100755 --- a/packages/node-client/tests/auth.test.js +++ b/packages/node-client/tests/auth.test.js @@ -16,6 +16,7 @@ test.before(async (t) => { t.context.stop = stop; const client = await nodeClient({ + namespaced: true, hostname:'http://localhost:8889', enableAuth: true, contractDir, diff --git a/packages/node-client/tests/jwt.test.js b/packages/node-client/tests/jwt.test.js index a85710e1..8f1a5220 100644 --- a/packages/node-client/tests/jwt.test.js +++ b/packages/node-client/tests/jwt.test.js @@ -28,6 +28,7 @@ test.before(async t => { t.context.stop = stop; const client = await nodeClient({ + namespaced: true, hostname:`http://localhost:${port}`, enableAuth: true, loginHandlerName: 'customLogin', diff --git a/packages/node-client/tests/main.test.js b/packages/node-client/tests/main.test.js index 0494adcc..d61d83d8 100755 --- a/packages/node-client/tests/main.test.js +++ b/packages/node-client/tests/main.test.js @@ -29,7 +29,7 @@ test(`Just to cause the jsonql-koa to run`, t => { }) */ -test.only('Should able to say Hello world using the shorthand version!' , async t => { +test('Should able to say Hello world using the shorthand version!' , async t => { // debug(t.context.client); const result = await t.context.client.helloWorld() t.is('Hello world!', result) diff --git a/packages/node-client/tests/ms.test.js b/packages/node-client/tests/ms.test.js index a4e4253a..5c4137e0 100644 --- a/packages/node-client/tests/ms.test.js +++ b/packages/node-client/tests/ms.test.js @@ -26,6 +26,7 @@ test.before(async t => { return app; }).then(app => { return client({ + namespaced: true, hostname: `${host}${portA}`, contractDir: join(baseDir, 'tmp', 'a', 'client') }) @@ -41,6 +42,7 @@ test.before(async t => { return app }).then(app => { return client({ + namespaced: true, hostname: `${host}${portB}`, contractDir: join(baseDir, 'tmp', 'b', 'client') }) diff --git a/packages/node-client/tests/socket.test.js b/packages/node-client/tests/socket.test.js index 7bb9f4ac..44c2f563 100644 --- a/packages/node-client/tests/socket.test.js +++ b/packages/node-client/tests/socket.test.js @@ -22,7 +22,7 @@ test.after(t => { }) test(`It should able to connect the server via http`, async t => { - const result = await t.context.client.query.helloWorld() + const result = await t.context.client.helloWorld() t.is('Hello world!', result) }) diff --git a/packages/node-client/tests/validation.test.js b/packages/node-client/tests/validation.test.js index 384980ae..ece07e1f 100644 --- a/packages/node-client/tests/validation.test.js +++ b/packages/node-client/tests/validation.test.js @@ -30,7 +30,7 @@ test.after(t => { // we don't test the valid one because it require a backend to set up test.only('Should able to pass with correct params', async t => { const c = t.context.client; - const user = await c.query.getUser(1) + const user = await c.getUser(1) t.is('Davide', user) debug(typeof JsonqlValidationError) @@ -38,10 +38,10 @@ test.only('Should able to pass with correct params', async t => { }) test('Should failed and throw JsonqlValidationError', async t => { - const c = t.context.client; + const c = t.context.client const e = await t.throwsAsync( async () => { - return await c.query.getUser('1') - } , JsonqlValidationError, 'Expect to throw a JsonqlValidationError' ) + return await c.getUser('1') + } , /* JsonqlValidationError */ null, 'Expect to throw a JsonqlValidationError' ) // @BUG the one that throw from inside is not the same as the one I am passing here? // why? they are all from the same source t.is(e.className , 'JsonqlValidationError') @@ -52,10 +52,10 @@ test('Should failed and throw JsonqlValidationError', async t => { test("Pass an index larger than the database size to cause it throw application error", async t => { const c = t.context.client; const e = await t.throwsAsync( async () => { - return await c.query.getUser(100) + return await c.getUser(100) // @BUG it was expect to throw a JsonqlResolverAppError The detail show its correct but the one throw is JsonqlError - }, JsonqlResolverAppError, + }, /*JsonqlResolverAppError*/ null, 'We should able to get a JsonqlResolverAppError back') t.is(e.className, 'JsonqlResolverAppError') -}); +}) -- Gitee From e6ee84b820b013410570992def6c8e4ac5009837 Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 2 Mar 2020 14:50:16 +0800 Subject: [PATCH 14/15] remove request as deps --- packages/node-client/package.json | 3 +- .../node-client/src/base/request-client.js | 29 ++----------------- packages/node-client/tests/jwt.test.js | 2 +- 3 files changed, 4 insertions(+), 30 deletions(-) diff --git a/packages/node-client/package.json b/packages/node-client/package.json index 9c6426f6..fbea0dcd 100755 --- a/packages/node-client/package.json +++ b/packages/node-client/package.json @@ -52,8 +52,7 @@ "jsonql-params-validator": "^1.5.2", "jsonql-utils": "^0.9.7", "lodash.merge": "^4.6.2", - "node-cache": "^5.1.0", - "request": "^2.88.2" + "node-cache": "^5.1.0" }, "optionalDependencies": { "@jsonql/ws": "^1.0.11" diff --git a/packages/node-client/src/base/request-client.js b/packages/node-client/src/base/request-client.js index 8ba3ce71..08ec0f1b 100755 --- a/packages/node-client/src/base/request-client.js +++ b/packages/node-client/src/base/request-client.js @@ -45,8 +45,9 @@ class JsonqlRequestClient extends JsonqlClient { debug('sending payload', display(payload,1)) const url = [this.__url__, querystring.stringify(this.__cacheBurst())].join('?') + const config = { method, headers: this.__createHeaders(headers) } - return request.jsonql(url, payload, { method }) + return request.jsonql(url, payload, config) .then(({result}) => { debug('got result from request', result) return this.__interceptor(payload, result) @@ -55,32 +56,6 @@ class JsonqlRequestClient extends JsonqlClient { debug('Error happens here in request', err) throw new Error(err) }) - /* - return new Promise((resolver, rejecter) => { - try { - request({ - json: true, - url: this.__url__, - headers: this.__createHeaders(headers), - qs: this.__cacheBurst(), - method: method, - body: payload - }, (error, response, body) => { - if (error) { - debug('an error occured', display(error)) - return rejecter(error); - } - debug('result body %O', body) - - const result = this.__interceptor(payload, body) - resolver(result) - }) - } catch(e) { - debug('error happens here!', e) - rejecter(e) - } - }) - */ } /** diff --git a/packages/node-client/tests/jwt.test.js b/packages/node-client/tests/jwt.test.js index 8f1a5220..7f1d9a85 100644 --- a/packages/node-client/tests/jwt.test.js +++ b/packages/node-client/tests/jwt.test.js @@ -10,7 +10,7 @@ const { contractKey, users } = require('./fixtures/options') const contractDir = join(__dirname, 'fixtures', 'jwt') const keysDir = join(__dirname, 'fixtures', 'keys') const port = 8890; -const username = 'joel'; +const username = 'joel' test.before(async t => { // make sure the folder is clean -- Gitee From 3294676caa980fb2a8142eb324b7327aad9b543f Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 2 Mar 2020 14:56:08 +0800 Subject: [PATCH 15/15] update readme and remove the request reference --- packages/node-client/README.md | 27 ++++++++++++++++--- .../node-client/src/base/request-client.js | 1 - 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/packages/node-client/README.md b/packages/node-client/README.md index 863767d5..40710bbd 100755 --- a/packages/node-client/README.md +++ b/packages/node-client/README.md @@ -1,11 +1,32 @@ [![NPM](https://nodei.co/npm/jsonql-node-client.png?compact=true)](https://npmjs.org/package/jsonql-node-client) -# json:ql node.js client +# jsonql node client This is the server to server client using node.js, all options identical to the browser client @jsonql/client +**BREAKING CHANGE IN 1.3.0** + +*We have add a `namespaced` option to the configuration, the default is `false` +It means, all your resolver no longer need to be `client.query` or `client.mutation`. +For using with socket client, it will still be under `client.socket` that is due to the way how its +constructed, and add to the client. + +If you pass `namespaced: true` then it will act exactly the same like before. Bear in mind, this option +will require you to have every single resolver to have a unique name, otherwise the name will get overwritten +by one another. Use it with caution.* + +## Installation + +```sh +$ npm i jsonql-node-client +``` + +You don't usually use this directly, this is part of the sub module for other jsonql modules. + --- -ISC [jsonql](http://jsonql.org) +Main website: [jsonql](http://jsonql.org) + +UNLICENSED -[NB](http://newbran.ch) & [T1S](http://to1source.cn) +[NEWBRAN LTD](http://newbran.ch) & [TO1SOURCE](http://to1source.cn) diff --git a/packages/node-client/src/base/request-client.js b/packages/node-client/src/base/request-client.js index 08ec0f1b..6e37fb18 100755 --- a/packages/node-client/src/base/request-client.js +++ b/packages/node-client/src/base/request-client.js @@ -1,7 +1,6 @@ /** * @1.3.0 replace request with flyio because request is deprecated */ -// const request = require('request') // @REMOVE const request = require('@to1source/request/jsonql') const querystring = require('querystring') const fsx = require('fs-extra') -- Gitee