diff --git a/packages/errors/dist/jsonql-errors.cjs.js b/packages/errors/dist/jsonql-errors.cjs.js index b6f380875bf86a01ff866320f74f840bdc319aa5..6a743a126c2239eb7c7a9f4501aa27147b7af0e8 100644 --- a/packages/errors/dist/jsonql-errors.cjs.js +++ b/packages/errors/dist/jsonql-errors.cjs.js @@ -1,2 +1,2 @@ -"use strict";function getErrorByStatus(r,o){switch(void 0===o&&(o=!1),r){case 401:return o?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}}Object.defineProperty(exports,"__esModule",{value:!0});var Jsonql406Error=function(r){function o(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t),this.message=t[0],this.detail=t[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 406},t.name.get=function(){return"Jsonql406Error"},Object.defineProperties(o,t),o}(Error),Jsonql500Error=function(r){function o(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t),this.message=t[0],this.detail=t[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 500},t.name.get=function(){return"Jsonql500Error"},Object.defineProperties(o,t),o}(Error),JsonqlAuthorisationError=function(r){function o(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t),this.message=t[0],this.detail=t[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 401},t.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(o,t),o}(Error),JsonqlContractAuthError=function(r){function o(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t),this.message=t[0],this.detail=t[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 401},t.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(o,t),o}(Error),JsonqlResolverAppError=function(r){function o(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t),this.message=t[0],this.detail=t[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 500},t.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(o,t),o}(Error),JsonqlResolverNotFoundError=function(r){function o(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t),this.message=t[0],this.detail=t[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var t={statusCode:{configurable:!0},name:{configurable:!0}};return t.statusCode.get=function(){return 404},t.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(o,t),o}(Error),JsonqlEnumError=function(r){function o(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t),this.message=t[0],this.detail=t[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(o,t),o}(Error),JsonqlTypeError=function(r){function o(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t),this.message=t[0],this.detail=t[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(o,t),o}(Error),JsonqlCheckerError=function(r){function o(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t),this.message=t[0],this.detail=t[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(o,t),o}(Error),JsonqlValidationError=function(r){function o(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t),this.message=t[0],this.detail=t[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(o,t),o}(Error),NO_ERROR_MSG="No message",NO_STATUS_CODE=-1,JsonqlError=function(r){function o(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t),this.message=t[0],this.detail=t[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var t={name:{configurable:!0},statusCode:{configurable:!0}};return t.name.get=function(){return"JsonqlError"},t.statusCode.get=function(){return NO_STATUS_CODE},Object.defineProperties(o,t),o}(Error),JsonqlServerError=function(r){function o(t,e){r.call(this,e),this.statusCode=t,this.className=o.name}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlServerError"},Object.defineProperties(o,t),o}(Error),errors=Object.freeze({Jsonql406Error:Jsonql406Error,Jsonql500Error:Jsonql500Error,JsonqlAuthorisationError:JsonqlAuthorisationError,JsonqlContractAuthError:JsonqlContractAuthError,JsonqlResolverAppError:JsonqlResolverAppError,JsonqlResolverNotFoundError:JsonqlResolverNotFoundError,JsonqlEnumError:JsonqlEnumError,JsonqlTypeError:JsonqlTypeError,JsonqlCheckerError:JsonqlCheckerError,JsonqlValidationError:JsonqlValidationError,JsonqlError:JsonqlError,JsonqlServerError:JsonqlServerError}),JsonqlError$1=JsonqlError,isKeyInObject=function(r,o){return!!Object.keys(r).filter(function(r){return o===r}).length};function clientErrorsHandler(r){if(isKeyInObject(r,"error")){var o=r.error,t=o.className,e=o.name,n=t||e,s=o.message||NO_ERROR_MSG,a=o.detail||o;if(n&&errors[n])throw new errors[t](s,a);throw new JsonqlError$1(s,a)}return r}var UNKNOWN_ERROR="unknown";function mapErrToName(r,o){return r.filter(function(r){return o instanceof r}).map(function(r){return r.name})}function getErrorNameByInstance(r,o){var t=mapErrToName(r,o);return t.length?t[0]:UNKNOWN_ERROR}function finalCatch(r){if(Array.isArray(r))throw new JsonqlValidationError("",r);var o=r.message||NO_ERROR_MSG,t=r.detail||r;switch(!0){case r instanceof Jsonql406Error:throw new Jsonql406Error(o,t);case r instanceof Jsonql500Error:throw new Jsonql500Error(o,t);case r instanceof JsonqlAuthorisationError:throw new JsonqlAuthorisationError(o,t);case r instanceof JsonqlContractAuthError:throw new JsonqlContractAuthError(o,t);case r instanceof JsonqlResolverAppError:throw new JsonqlResolverAppError(o,t);case r instanceof JsonqlResolverNotFoundError:throw new JsonqlResolverNotFoundError(o,t);case r instanceof JsonqlEnumError:throw new JsonqlEnumError(o,t);case r instanceof JsonqlTypeError:throw new JsonqlTypeError(o,t);case r instanceof JsonqlCheckerError:throw new JsonqlCheckerError(o,t);case r instanceof JsonqlValidationError:throw new JsonqlValidationError(o,t);case r instanceof JsonqlServerError:throw new JsonqlServerError(o,t);default:throw new JsonqlError(o,t)}}var JSONQL_ERRORS_INFO="version: 1.1.1 module: cjs";exports.JSONQL_ERRORS_INFO=JSONQL_ERRORS_INFO,exports.Jsonql406Error=Jsonql406Error,exports.Jsonql500Error=Jsonql500Error,exports.JsonqlAuthorisationError=JsonqlAuthorisationError,exports.JsonqlCheckerError=JsonqlCheckerError,exports.JsonqlContractAuthError=JsonqlContractAuthError,exports.JsonqlEnumError=JsonqlEnumError,exports.JsonqlError=JsonqlError,exports.JsonqlResolverAppError=JsonqlResolverAppError,exports.JsonqlResolverNotFoundError=JsonqlResolverNotFoundError,exports.JsonqlServerError=JsonqlServerError,exports.JsonqlTypeError=JsonqlTypeError,exports.JsonqlValidationError=JsonqlValidationError,exports.UNKNOWN_ERROR=UNKNOWN_ERROR,exports.clientErrorsHandler=clientErrorsHandler,exports.finalCatch=finalCatch,exports.getErrorByStatus=getErrorByStatus,exports.getErrorNameByInstance=getErrorNameByInstance; +"use strict";function getErrorByStatus(r,o){switch(void 0===o&&(o=!1),r){case 401:return o?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}}Object.defineProperty(exports,"__esModule",{value:!0});var Jsonql406Error=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(o,e),o}(Error),Jsonql500Error=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(o,e),o}(Error),JsonqlAuthorisationError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(o,e),o}(Error),JsonqlContractAuthError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(o,e),o}(Error),JsonqlResolverAppError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(o,e),o}(Error),global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},isBrowser=function(){try{if(window||document)return!0}catch(r){}return!1},isNode=function(){try{if(!isBrowser()&&global$1)return!0}catch(r){}return!1};function whereAmI(){return isBrowser()?"browser":isNode()?"node":"unknown"}var JsonqlBaseError=function(r){function o(){for(var o=[],e=arguments.length;e--;)o[e]=arguments[e];r.apply(this,o)}return r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o,o.where=function(){return whereAmI()},o}(Error),JsonqlResolverNotFoundError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,Error.captureStackTrace&&Error.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(o,e),o}(JsonqlBaseError),JsonqlEnumError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(o,e),o}(Error),JsonqlTypeError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(o,e),o}(Error),JsonqlCheckerError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,r.captureStackTrace&&r.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(o,e),o}(Error),JsonqlValidationError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,Error.captureStackTrace&&Error.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(o,e),o}(JsonqlBaseError),NO_ERROR_MSG="No message",NO_STATUS_CODE=-1,JsonqlError=function(r){function o(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=o.name,Error.captureStackTrace&&Error.captureStackTrace(this,o)}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return NO_STATUS_CODE},Object.defineProperties(o,e),o}(JsonqlBaseError),JsonqlServerError=function(r){function o(e,t){r.call(this,t),this.statusCode=e,this.className=o.name}r&&(o.__proto__=r),o.prototype=Object.create(r&&r.prototype),o.prototype.constructor=o;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(o,e),o}(Error),errors=Object.freeze({Jsonql406Error:Jsonql406Error,Jsonql500Error:Jsonql500Error,JsonqlAuthorisationError:JsonqlAuthorisationError,JsonqlContractAuthError:JsonqlContractAuthError,JsonqlResolverAppError:JsonqlResolverAppError,JsonqlResolverNotFoundError:JsonqlResolverNotFoundError,JsonqlEnumError:JsonqlEnumError,JsonqlTypeError:JsonqlTypeError,JsonqlCheckerError:JsonqlCheckerError,JsonqlValidationError:JsonqlValidationError,JsonqlError:JsonqlError,JsonqlServerError:JsonqlServerError}),JsonqlError$1=JsonqlError,isKeyInObject=function(r,o){return!!Object.keys(r).filter(function(r){return o===r}).length};function clientErrorsHandler(r){if(isKeyInObject(r,"error")){var o=r.error,e=o.className,t=o.name,n=e||t,s=o.message||NO_ERROR_MSG,a=o.detail||o;if(n&&errors[n])throw new errors[e](s,a);throw new JsonqlError$1(s,a)}return r}var UNKNOWN_ERROR="unknown";function mapErrToName(r,o){return r.filter(function(r){return o instanceof r}).map(function(r){return r.name})}function getErrorNameByInstance(r,o){var e=mapErrToName(r,o);return e.length?e[0]:UNKNOWN_ERROR}function finalCatch(r){if(Array.isArray(r))throw new JsonqlValidationError("",r);var o=r.message||NO_ERROR_MSG,e=r.detail||r;switch(!0){case r instanceof Jsonql406Error:throw new Jsonql406Error(o,e);case r instanceof Jsonql500Error:throw new Jsonql500Error(o,e);case r instanceof JsonqlAuthorisationError:throw new JsonqlAuthorisationError(o,e);case r instanceof JsonqlContractAuthError:throw new JsonqlContractAuthError(o,e);case r instanceof JsonqlResolverAppError:throw new JsonqlResolverAppError(o,e);case r instanceof JsonqlResolverNotFoundError:throw new JsonqlResolverNotFoundError(o,e);case r instanceof JsonqlEnumError:throw new JsonqlEnumError(o,e);case r instanceof JsonqlTypeError:throw new JsonqlTypeError(o,e);case r instanceof JsonqlCheckerError:throw new JsonqlCheckerError(o,e);case r instanceof JsonqlValidationError:throw new JsonqlValidationError(o,e);case r instanceof JsonqlServerError:throw new JsonqlServerError(o,e);default:throw new JsonqlError(o,e)}}var JSONQL_ERRORS_INFO="version: 1.1.2 module: cjs";exports.JSONQL_ERRORS_INFO=JSONQL_ERRORS_INFO,exports.Jsonql406Error=Jsonql406Error,exports.Jsonql500Error=Jsonql500Error,exports.JsonqlAuthorisationError=JsonqlAuthorisationError,exports.JsonqlCheckerError=JsonqlCheckerError,exports.JsonqlContractAuthError=JsonqlContractAuthError,exports.JsonqlEnumError=JsonqlEnumError,exports.JsonqlError=JsonqlError,exports.JsonqlResolverAppError=JsonqlResolverAppError,exports.JsonqlResolverNotFoundError=JsonqlResolverNotFoundError,exports.JsonqlServerError=JsonqlServerError,exports.JsonqlTypeError=JsonqlTypeError,exports.JsonqlValidationError=JsonqlValidationError,exports.UNKNOWN_ERROR=UNKNOWN_ERROR,exports.clientErrorsHandler=clientErrorsHandler,exports.finalCatch=finalCatch,exports.getErrorByStatus=getErrorByStatus,exports.getErrorNameByInstance=getErrorNameByInstance; //# sourceMappingURL=jsonql-errors.cjs.js.map diff --git a/packages/errors/dist/jsonql-errors.umd.js b/packages/errors/dist/jsonql-errors.umd.js index 1df7d033092cef914d7ed09b416d032421a83587..314ae83f0c76ded85296011648188c9302bdb4b9 100644 --- a/packages/errors/dist/jsonql-errors.umd.js +++ b/packages/errors/dist/jsonql-errors.umd.js @@ -1,2 +1,2 @@ -!function(r,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((r=r||self).jsonqlErrors={})}(this,function(r){"use strict";var t=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(t,e),t}(Error),e=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(t,e),t}(Error),o=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(t,e),t}(Error),n=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(t,e),t}(Error),a=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(t,e),t}(Error),s=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(t,e),t}(Error),c=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(t,e),t}(Error),i=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(t,e),t}(Error),u=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(t,e),t}(Error),p=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(t,e),t}(Error),l="No message",f=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(t,e),t}(Error),h=function(r){function t(e,o){r.call(this,o),this.statusCode=e,this.className=t.name}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(t,e),t}(Error),m=Object.freeze({Jsonql406Error:t,Jsonql500Error:e,JsonqlAuthorisationError:o,JsonqlContractAuthError:n,JsonqlResolverAppError:a,JsonqlResolverNotFoundError:s,JsonqlEnumError:c,JsonqlTypeError:i,JsonqlCheckerError:u,JsonqlValidationError:p,JsonqlError:f,JsonqlServerError:h}),g=f,d=function(r,t){return!!Object.keys(r).filter(function(r){return t===r}).length};var E="unknown";r.JSONQL_ERRORS_INFO="version: 1.1.1 module: umd",r.Jsonql406Error=t,r.Jsonql500Error=e,r.JsonqlAuthorisationError=o,r.JsonqlCheckerError=u,r.JsonqlContractAuthError=n,r.JsonqlEnumError=c,r.JsonqlError=f,r.JsonqlResolverAppError=a,r.JsonqlResolverNotFoundError=s,r.JsonqlServerError=h,r.JsonqlTypeError=i,r.JsonqlValidationError=p,r.UNKNOWN_ERROR=E,r.clientErrorsHandler=function(r){if(d(r,"error")){var t=r.error,e=t.className,o=t.name,n=e||o,a=t.message||l,s=t.detail||t;if(n&&m[n])throw new m[e](a,s);throw new g(a,s)}return r},r.finalCatch=function(r){if(Array.isArray(r))throw new p("",r);var m=r.message||l,g=r.detail||r;switch(!0){case r instanceof t:throw new t(m,g);case r instanceof e:throw new e(m,g);case r instanceof o:throw new o(m,g);case r instanceof n:throw new n(m,g);case r instanceof a:throw new a(m,g);case r instanceof s:throw new s(m,g);case r instanceof c:throw new c(m,g);case r instanceof i:throw new i(m,g);case r instanceof u:throw new u(m,g);case r instanceof p:throw new p(m,g);case r instanceof h:throw new h(m,g);default:throw new f(m,g)}},r.getErrorByStatus=function(r,t){switch(void 0===t&&(t=!1),r){case 401:return t?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}},r.getErrorNameByInstance=function(r,t){var e=function(r,t){return r.filter(function(r){return t instanceof r}).map(function(r){return r.name})}(r,t);return e.length?e[0]:E},Object.defineProperty(r,"__esModule",{value:!0})}); +!function(r,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((r=r||self).jsonqlErrors={})}(this,function(r){"use strict";var t=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(t,e),t}(Error),e=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(t,e),t}(Error),o=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(t,e),t}(Error),n=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(t,e),t}(Error),a=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(t,e),t}(Error),c="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},s=function(){try{if(window||document)return!0}catch(r){}return!1},i=function(){try{if(!s()&&c)return!0}catch(r){}return!1};var u=function(r){function t(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t)}return r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t,t.where=function(){return s()?"browser":i()?"node":"unknown"},t}(Error),p=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,Error.captureStackTrace&&Error.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(t,e),t}(u),l=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(t,e),t}(Error),f=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(t,e),t}(Error),h=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(t,e),t}(Error),d=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,Error.captureStackTrace&&Error.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(t,e),t}(u),m="No message",g=function(r){function t(){for(var e=[],o=arguments.length;o--;)e[o]=arguments[o];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,Error.captureStackTrace&&Error.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return-1},Object.defineProperties(t,e),t}(u),y=function(r){function t(e,o){r.call(this,o),this.statusCode=e,this.className=t.name}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(t,e),t}(Error),E=Object.freeze({Jsonql406Error:t,Jsonql500Error:e,JsonqlAuthorisationError:o,JsonqlContractAuthError:n,JsonqlResolverAppError:a,JsonqlResolverNotFoundError:p,JsonqlEnumError:l,JsonqlTypeError:f,JsonqlCheckerError:h,JsonqlValidationError:d,JsonqlError:g,JsonqlServerError:y}),_=g,b=function(r,t){return!!Object.keys(r).filter(function(r){return t===r}).length};var q="unknown";r.JSONQL_ERRORS_INFO="version: 1.1.2 module: umd",r.Jsonql406Error=t,r.Jsonql500Error=e,r.JsonqlAuthorisationError=o,r.JsonqlCheckerError=h,r.JsonqlContractAuthError=n,r.JsonqlEnumError=l,r.JsonqlError=g,r.JsonqlResolverAppError=a,r.JsonqlResolverNotFoundError=p,r.JsonqlServerError=y,r.JsonqlTypeError=f,r.JsonqlValidationError=d,r.UNKNOWN_ERROR=q,r.clientErrorsHandler=function(r){if(b(r,"error")){var t=r.error,e=t.className,o=t.name,n=e||o,a=t.message||m,c=t.detail||t;if(n&&E[n])throw new E[e](a,c);throw new _(a,c)}return r},r.finalCatch=function(r){if(Array.isArray(r))throw new d("",r);var c=r.message||m,s=r.detail||r;switch(!0){case r instanceof t:throw new t(c,s);case r instanceof e:throw new e(c,s);case r instanceof o:throw new o(c,s);case r instanceof n:throw new n(c,s);case r instanceof a:throw new a(c,s);case r instanceof p:throw new p(c,s);case r instanceof l:throw new l(c,s);case r instanceof f:throw new f(c,s);case r instanceof h:throw new h(c,s);case r instanceof d:throw new d(c,s);case r instanceof y:throw new y(c,s);default:throw new g(c,s)}},r.getErrorByStatus=function(r,t){switch(void 0===t&&(t=!1),r){case 401:return t?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}},r.getErrorNameByInstance=function(r,t){var e=function(r,t){return r.filter(function(r){return t instanceof r}).map(function(r){return r.name})}(r,t);return e.length?e[0]:q},Object.defineProperty(r,"__esModule",{value:!0})}); //# sourceMappingURL=jsonql-errors.umd.js.map diff --git a/packages/errors/package.json b/packages/errors/package.json index c259d7b9acf3e01bdb302c565d5db95d8e748266..c7bd6fd53a87b34fa35a35689bdc395387ca3f2c 100644 --- a/packages/errors/package.json +++ b/packages/errors/package.json @@ -1,13 +1,13 @@ { "name": "jsonql-errors", - "version": "1.1.1", + "version": "1.1.2", "description": "Jsonql js error classes use across the projects", "main": "dist/jsonql-errors.cjs.js", "module": "index.js", "browser": "dist/jsonql-errors.umd.js", "scripts": { "prepare": "npm run build", - "test": "ava", + "test": "ava --verbose", "test:server": "ava ./tests/server.test.js", "test:run": "node ./tests/helpers/run.js", "test:fn": "ava ./tests/fn.test.js", @@ -25,7 +25,7 @@ "Error" ], "devDependencies": { - "ava": "^2.2.0", + "ava": "^2.3.0", "debug": "^4.1.1", "esm": "^3.2.25", "fs-extra": "^8.1.0", diff --git a/packages/errors/src/error-base.js b/packages/errors/src/error-base.js new file mode 100644 index 0000000000000000000000000000000000000000..19b2e09f3a1128aec4bcac9622769f0b2e5982f5 --- /dev/null +++ b/packages/errors/src/error-base.js @@ -0,0 +1,13 @@ +// The base Error of all +import whereAmI from './where-am-i' + +export default class JsonqlBaseError extends Error { + constructor(...args) { + super(...args) + } + + static where() { + return whereAmI() + } + +} diff --git a/packages/errors/src/error.js b/packages/errors/src/error.js index e8ebfb93873e6b49b954e34547515eb1fe5afa98..179834378c22219179edfb779f80ee53cd5a5beb 100644 --- a/packages/errors/src/error.js +++ b/packages/errors/src/error.js @@ -1,12 +1,12 @@ import { NO_STATUS_CODE } from 'jsonql-constants'; - +import JsonqlBaseError from './error-base' /** * This is a custom error to throw whenever a error happen inside the jsonql * This help us to capture the right error, due to the call happens in sequence * @param {string} message to tell what happen * @param {mixed} extra things we want to add, 500? */ -export default class JsonqlError extends Error { +export default class JsonqlError extends JsonqlBaseError { constructor(...args) { super(...args); @@ -16,7 +16,8 @@ export default class JsonqlError extends Error { this.className = JsonqlError.name; if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlError); + Error.captureStackTrace(this, JsonqlError) + // this.detail = this.stack; } } diff --git a/packages/errors/src/final-catch.js b/packages/errors/src/final-catch.js index 02b49352bd4ec3efeab5143ab0c758dffc3a804c..a6b7001b396279738b1c79f890df519b117acb4b 100644 --- a/packages/errors/src/final-catch.js +++ b/packages/errors/src/final-catch.js @@ -30,7 +30,7 @@ export default function finalCatch(e) { if (Array.isArray(e)) { // if we want the message then I will have to create yet another function // to wrap this function to provide the name prop - throw new JsonqlValidationError('', e); + throw new JsonqlValidationError('', e) } const msg = e.message || NO_ERROR_MSG; const detail = e.detail || e; diff --git a/packages/errors/src/resolver-not-found-error.js b/packages/errors/src/resolver-not-found-error.js index fd6eeadd34c52b14dedd892efabfc33e0b47210d..14d8d90d2762c447e4c0f7c9c76826641e823f18 100644 --- a/packages/errors/src/resolver-not-found-error.js +++ b/packages/errors/src/resolver-not-found-error.js @@ -1,11 +1,11 @@ - +import JsonqlBaseError from './error-base' /** * This is a custom error to throw when could not find the resolver * This help us to capture the right error, due to the call happens in sequence * @param {string} message to tell what happen * @param {mixed} extra things we want to add, 500? */ -export default class JsonqlResolverNotFoundError extends Error { +export default class JsonqlResolverNotFoundError extends JsonqlBaseError { constructor(...args) { super(...args); diff --git a/packages/errors/src/validation-error.js b/packages/errors/src/validation-error.js index 968763f7cc9df072b057b38a0ba063d02a009f79..420948c91b68ad29db472f0069c2c1eb1b5ec713 100644 --- a/packages/errors/src/validation-error.js +++ b/packages/errors/src/validation-error.js @@ -1,6 +1,7 @@ // custom validation error class +import JsonqlBaseError from './error-base' // when validaton failed -export default class JsonqlValidationError extends Error { +export default class JsonqlValidationError extends JsonqlBaseError { constructor(...args) { super(...args); diff --git a/packages/errors/src/where-am-i.js b/packages/errors/src/where-am-i.js new file mode 100644 index 0000000000000000000000000000000000000000..ec07ed67f4953542384070a7aba0b0d6083fda20 --- /dev/null +++ b/packages/errors/src/where-am-i.js @@ -0,0 +1,35 @@ +/** + * some time it's hard to tell where the error is throw from + * because client server throw the same, therefore this util fn + * to add a property to the error object to tell if it's throw + * from client or server + * + */ + +const isBrowser = () => { + try { + if (window || document) { + return true; + } + } catch(e) {} + return false; +} + +const isNode = () => { + try { + if (!isBrowser() && global) { + return true; + } + } catch(e) {} + return false; +} + +export default function whereAmI() { + if (isBrowser()) { + return 'browser' + } + if (isNode()) { + return 'node' + } + return 'unknown' +} diff --git a/packages/errors/tests/main.test.js b/packages/errors/tests/main.test.js index 16a712837808c0869ac9fa7b06e5c58937d98899..bb81a672417a6150cca1833b3871ae9761ed9c36 100644 --- a/packages/errors/tests/main.test.js +++ b/packages/errors/tests/main.test.js @@ -1,26 +1,26 @@ // just to throw a few and test them out -const test = require('ava'); +const test = require('ava') const { JsonqlResolverAppError, JsonqlResolverNotFoundError, finalCatch, JsonqlError -} = require('../dist/jsonql-errors.cjs'); -const resolver = require('./fixtures/resolver'); -const debug = require('debug')('jsonql-errors:test:main'); -const justThrow = require('./helpers/throw-some-error'); +} = require('../dist/jsonql-errors.cjs') +const resolver = require('./fixtures/resolver') +const debug = require('debug')('jsonql-errors:test:main') +const justThrow = require('./helpers/throw-some-error') const isKeyInObject = (obj, key) => { const keys = Object.keys(obj); return !!keys.filter(k => key === k).length; -}; +} test('Just need to test this isKeyInObject function', t => { let obj = {error: false}; t.is(true, isKeyInObject(obj, 'error')); - -}); + +}) test('It should throw a resolver application error', t => { @@ -29,33 +29,39 @@ test('It should throw a resolver application error', t => { return resolver(); } , JsonqlResolverAppError, 'Throw a dummy error'); + + t.is(error.className, 'JsonqlResolverAppError'); t.true(typeof error.detail === 'object'); t.is(error.message, 'Dummy'); -}); +}) test('It should throw a JsonqlResolverNotFoundError with the wrong name', t => { const name = 'wrongName'; const fn = () => { try { - const contract = {query: {whatever: {public: true}}}; + const contract = {query: {whatever: {public: true}}} const type = 'queryx'; return contract[type][name]; } catch(e) { - throw new JsonqlResolverNotFoundError(name, e); + throw new JsonqlResolverNotFoundError(name, e) } - }; + } const error = t.throws(() => { fn(); - }, JsonqlResolverNotFoundError, 'It should throw a JsonqlResolverNotFoundError'); + }, JsonqlResolverNotFoundError, 'It should throw a JsonqlResolverNotFoundError') + + // t.is(error.where, 'node') + + debug(error) - t.is(error.message, name); -}); + t.is(error.message, name) +}) test("Very dummy test to test the test Error instance", async t => { await t.throwsAsync(async () => { - return await justThrow().catch(finalCatch); - }, JsonqlError, 'just throw a JsonqlError'); + return await justThrow().catch(finalCatch) + }, JsonqlError, 'just throw a JsonqlError') -}); +}) diff --git a/packages/errors/tests/server.test.js b/packages/errors/tests/server.test.js index a854b4a774b7a42c15839edd49f4d3cee3bb1bcf..3923f184a5ab225e9d7545089f1e611a0accfd0c 100644 --- a/packages/errors/tests/server.test.js +++ b/packages/errors/tests/server.test.js @@ -1,11 +1,11 @@ // test with the server side throw error -const test = require('ava'); -const server = require('./helpers/server-throw'); -const superkoa = require('superkoa'); +const test = require('ava') +const server = require('./helpers/server-throw') +const superkoa = require('superkoa') test.before( t => { - t.context.app = server(true); -}); + t.context.app = server(true) +}) test('It should able to catch the 500 and extract a payload', async t => { let res = await superkoa(t.context.app) @@ -16,10 +16,10 @@ test('It should able to catch the 500 and extract a payload', async t => { helloWorld: { args: [] } - }); + }) // console.info(res.body); - t.is(500, res.status); + t.is(500, res.status) -}); +}) diff --git a/packages/koa/package.json b/packages/koa/package.json index 71fe3dbae405667311b36ebe7df0397a7a4dbe5e..a6f9302e97f67629fa1623ca3a3454a177154405 100755 --- a/packages/koa/package.json +++ b/packages/koa/package.json @@ -26,6 +26,7 @@ "test:gen": "DEBUG=jsonql* ava ./tests/contract.test.js", "test:jsonp": "DEBUG=jsonql* ava --verbose ./tests/jsonp.test.js", "test:chain": "DEBUG=jsonql* ava --verbose ./tests/chain-fn.test.js", + "test:clients": "DEBUG=jsonql* ava --verbose ./tests/node-client.test.js", "web-console": "DEBUG=jsonql-koa*,jsonql-web-console* node ./tests/helpers/browser.js", "contract": "node ./node_modules/jsonql-contract/cmd.js ./tests/fixtures/resolvers ./tests/fixtures/contracts" }, @@ -43,13 +44,13 @@ "fs-extra": "^8.1.0", "jsonql-constants": "^1.7.9", "jsonql-contract": "^1.7.7", - "jsonql-errors": "^1.1.1", + "jsonql-errors": "^1.1.2", "jsonql-jwt": "^1.2.5", - "jsonql-node-client": "^1.1.3", - "jsonql-params-validator": "^1.4.3", - "jsonql-resolver": "^0.5.0", + "jsonql-node-client": "^1.1.5", + "jsonql-params-validator": "^1.4.4", + "jsonql-resolver": "^0.6.2", "jsonql-web-console": "^0.4.3", - "koa": "^2.7.0", + "koa": "^2.8.1", "koa-compose": "^4.1.0", "lodash": "^4.17.15", "node-cache": "^4.2.1" @@ -60,7 +61,7 @@ ], "license": "MIT", "devDependencies": { - "ava": "^2.2.0", + "ava": "^2.3.0", "jwt-decode": "^2.2.0", "koa-bodyparser": "^4.2.1", "nyc": "^14.1.1", diff --git a/packages/koa/src/lib/config-check/index.js b/packages/koa/src/lib/config-check/index.js index f166f154eb6eb6165522e729de65975b372a57e2..e911bcf498890b2eeab02b5f7d60f26e39464d4f 100644 --- a/packages/koa/src/lib/config-check/index.js +++ b/packages/koa/src/lib/config-check/index.js @@ -20,6 +20,7 @@ const applyGetContract = function(config) { config.contract = contract; // @ 1.3.4 - also generate the public contract if (config.withPublicContract) { + debug(`get cache public contract`) getContract(config, true) } } else { @@ -28,6 +29,7 @@ const applyGetContract = function(config) { .then(contract => { // @ 1.3.4 if (config.withPublicContract) { + debug(`get new public contract`) getContract(config, true) } return contract; diff --git a/packages/koa/src/lib/index.js b/packages/koa/src/lib/index.js index 93c9ed181dafd74b82cad8d481990427a598aa13..3fdbf579a5a4a6e67c24292541a34e5d68b1211a 100755 --- a/packages/koa/src/lib/index.js +++ b/packages/koa/src/lib/index.js @@ -30,9 +30,6 @@ const { extractParamsFromContract } = require('./utils') -// const validateAndCall = require('./validate-and-call') -// const searchResolvers = require('./search-resolvers') - const getContract = require('./contract-generator') const processJwtKeys = require('./config-check/process-jwt-keys') const { setter, getter } = require('./cache') @@ -52,9 +49,7 @@ module.exports = { printError, forbiddenHandler, ctxErrorHandler, - // individual import - // validateAndCall, - // searchResolvers, + // v1.3.8 resolveMethod, isJsonqlPath, diff --git a/packages/koa/src/lib/old/resolve-method.js b/packages/koa/src/lib/old/resolve-method.js deleted file mode 100644 index 857511692ae8312d1ef0737fdd4e3f9a2865c5ae..0000000000000000000000000000000000000000 --- a/packages/koa/src/lib/old/resolve-method.js +++ /dev/null @@ -1,96 +0,0 @@ -// this was in the core-middleware now make this standalone for use in -// two middlewares -const { join } = require('path') -const { - JsonqlResolverNotFoundError, - JsonqlResolverAppError, - JsonqlValidationError, - JsonqlAuthorisationError -} = require('jsonql-errors') -const searchResolvers = require('./search-resolvers') -const validateAndCall = require('./validate-and-call') -const { - getDebug, - printError, - handleOutput, - extractArgsFromPayload, - ctxErrorHandler, - packResult -} = require('./utils') -const { provideUserdata } = require('jsonql-jwt') -const { - DEFAULT_RESOLVER_IMPORT_FILE_NAME, - MODULE_TYPE -} = require('jsonql-constants') -const debug = getDebug('resolve-method') - -/** - * New for ES6 module features - * @param {string} resolverDir resolver directory - * @param {string} type of resolver - * @param {string} resolverName name of resolver - * @return {function} the imported resolver - */ -function importFromModule(resolverDir, type, resolverName) { - debug(resolverDir, type, resolverName) - const resolvers = require( join(resolverDir, DEFAULT_RESOLVER_IMPORT_FILE_NAME) ) - return resolvers[type + resolverName] -} - -/** - * The method call has this signature - * @param {object} ctx Koa context - * @param {string} type of calls - * @param {object} opts configuration - * @param {object} contract to search via the file name info - * @return {mixed} depends on the contract - */ -const resolveMethod = async (ctx, type, opts, contract) => { - const { payload, resolverName, userdata } = ctx.state.jsonql; - debug('resolveMethod', resolverName, payload, type) - // There must be only one method call - const renderHandler = handleOutput(opts) - // first try to catch the resolve error - try { - let fn; - const { sourceType } = contract; - if (sourceType === MODULE_TYPE) { - const { resolverDir } = opts; - fn = importFromModule(resolverDir, type, resolverName) - } else { - fn = require(searchResolvers(resolverName, type, opts, contract)) - } - const args = extractArgsFromPayload(payload, type) - // here we could apply the userdata to the method - const result = await validateAndCall( - provideUserdata(fn, userdata), // always call it - args, - contract, - type, - resolverName, - opts) - // @TODO if we need to check returns in the future - debug('called and now serve up', result) - return renderHandler(ctx, packResult(result)) - } catch (e) { - debug('resolveMethod error', e) - let errorClassName = 'JsonqlError'; - switch (true) { - case (e instanceof JsonqlResolverNotFoundError): - errorClassName = 'JsonqlResolverNotFoundError'; - break; - case (e instanceof JsonqlAuthorisationError): - errorClassName = 'JsonqlAuthorisationError'; - break; - case (e instanceof JsonqlValidationError): - errorClassName = 'JsonqlValidationError'; - break; - case (e instanceof JsonqlResolverAppError): - errorClassName = 'JsonqlResolverAppError'; - break; - } - return ctxErrorHandler(ctx, errorClassName, e); - } -} -// export -module.exports = resolveMethod; diff --git a/packages/koa/src/lib/old/search-resolvers.js b/packages/koa/src/lib/old/search-resolvers.js deleted file mode 100755 index b07f9dc795cc6ab02caab6242f20b2954e68c638..0000000000000000000000000000000000000000 --- a/packages/koa/src/lib/old/search-resolvers.js +++ /dev/null @@ -1,60 +0,0 @@ -// search for the resolver location -const fs = require('fs') -const { join } = require('path') -const debug = require('debug')('jsonql-koa:lib:search') - -const { JsonqlResolverNotFoundError } = require('jsonql-errors') -const { getPathToFn } = require('./utils') -const prod = process.env.NODE_ENV === 'production'; - -/** - * Using the contract to find the function to call - * @param {string} type of resolver - * @param {string} name of resolver - * @param {object} contract to search from - * @return {string} file path to function - */ -function findFromContract(type, name, contract) { - if (contract[type] && contract[type][name] && contract[type][name].file) { - if (fs.existsSync(contract[type][name].file)) { - return contract[type][name].file; - } - } - return false; -} - -/** - * search for the file starting with - * 1. Is the path in the contract (or do we have a contract file) - * 2. if not then resolvers/query/name-of-call/index.js (query swap with mutation) - * 3. then resolvers/query/name-of-call.js - * @param {string} name of the resolver - * @param {string} type of the resolver - * @param {object} opts options - * @param {object} contract full version - * @return {string} the path to function - */ -module.exports = function searchResolvers(name, type, opts, contract) { - try { - const json = typeof contract === 'string' ? JSON.parse(contract) : contract; - const search = findFromContract(type, name, json) - if (search !== false) { - return search; - } - // search by running - const filePath = getPathToFn(name, type, opts) - if (filePath) { - return filePath; - } - const debugMsg = `${name} not found!`; - debug(debugMsg); - const msg = prod ? 'NOT FOUND!' : debugMsg; - throw new JsonqlResolverNotFoundError(msg) - } catch(e) { - if (e instanceof JsonqlResolverNotFoundError) { - throw new JsonqlResolverNotFoundError(e) - } else { - throw new JsonqError(e) - } - } -} diff --git a/packages/koa/src/lib/old/validate-and-call.js b/packages/koa/src/lib/old/validate-and-call.js deleted file mode 100644 index 3e7fc25467fefb6abb7073a2815c54473d375c62..0000000000000000000000000000000000000000 --- a/packages/koa/src/lib/old/validate-and-call.js +++ /dev/null @@ -1,62 +0,0 @@ -// validation wrapper -const { AUTH_TYPE, HSA_ALGO, RSA_ALGO } = require('jsonql-constants') -const { validateSync, isString } = require('jsonql-params-validator') -const { JsonqlValidationError } = require('jsonql-errors') -const { loginResultToJwt } = require('jsonql-jwt') - -const { extractParamsFromContract, getDebug } = require('./utils') - -const debug = getDebug('validate-and-call') -// for caching -var resultMethod; - -/** - * get the encode method also cache it - * @param {object} opts configuration - * @return {function} encode method - */ -const getEncodeJwtMethod = opts => { - if (resultMethod && typeof resultMethod === 'function') { - return resultMethod; - } - let key = isString(opts.useJwt) ? opts.useJwt : opts.privateKey; - let alg = isString(opts.useJwt) ? HSA_ALGO : RSA_ALGO; - // add jwtTokenOption for the extra configuration for generate token - return loginResultToJwt(key, opts.jwtTokenOption, alg) -} - -/** - * This will hijack some of the function for the auth type - * @param {string} type of resolver we only after the auth type - * @param {string} name of the resolver function - * @param {object} opts configuration - * @param {object} contract the contract.json - */ -const applyJwtMethod = (type, name, opts, contract) => { - return result => { - if (type === AUTH_TYPE && name === opts.loginHandlerName && opts.enableAuth && opts.useJwt) { - return getEncodeJwtMethod(opts)(result) - } - return result; - } -} - -/** - * Main method to replace the fn.apply call inside the core method - * @param {function} fn the resolver to get execute - * @param {array} args the argument list - * @param {object} contract the full contract.json - * @param {string} type query | mutation - * @param {string} name of the function - * @param {object} opts configuration option to use in the future - * @return {object} now return a promise that resolve whatever the resolver is going to return and packed - */ -module.exports = function validateAndCall(fn, args, contract, type, name, opts) { - const { params } = extractParamsFromContract(contract, type, name); - let errors = validateSync(args, params); - if (errors.length) { - throw new JsonqlValidationError(name, errors); - } - return Promise.resolve(fn.apply(null, args)) - .then(applyJwtMethod(type, name, opts, contract)) -} diff --git a/packages/koa/tests/fixtures/html/index.html b/packages/koa/tests/fixtures/html/index.html new file mode 100644 index 0000000000000000000000000000000000000000..d1fdcefb8fae3b9a5759efe6bdaad4f1dfabd1ba --- /dev/null +++ b/packages/koa/tests/fixtures/html/index.html @@ -0,0 +1,9 @@ + + + + dummy + + + dummy + + diff --git a/packages/koa/tests/fixtures/resolvers/mutation/update-ms-service.js b/packages/koa/tests/fixtures/resolvers/mutation/update-ms-service.js new file mode 100644 index 0000000000000000000000000000000000000000..d93ef8fce75dff70d4c8dba6e43f6d240b0ce58c --- /dev/null +++ b/packages/koa/tests/fixtures/resolvers/mutation/update-ms-service.js @@ -0,0 +1,14 @@ +const debug = require('debug')('jsonql-koa:mutation:update-ms-service') +/** + * this will be calling a microserivce setup using the nodeClient + * @param {string} payload incoming + * @return {string} msg return from nodeClient + */ +module.exports = async function updateMsService(payload) { + + debug('payload', payload) + + const client = await updateMsService.clients('nodeClient0') + + return client.query.msService(payload) +} diff --git a/packages/koa/tests/fixtures/sub/contract/contract.json b/packages/koa/tests/fixtures/sub/contract/contract.json new file mode 100644 index 0000000000000000000000000000000000000000..0b53f8751a4ac515ced6c67ef39d80d0b31a17a1 --- /dev/null +++ b/packages/koa/tests/fixtures/sub/contract/contract.json @@ -0,0 +1,51 @@ +{ + "query": { + "msService": { + "file": "/home/joel/projects/open-source/jsonql/packages/koa/tests/fixtures/sub/resolver/query/ms-service.js", + "description": false, + "params": [ + { + "type": [ + "string" + ], + "name": "msg", + "description": "incoming message" + } + ], + "returns": [ + { + "type": [ + "string" + ], + "description": "out going message" + } + ] + } + }, + "mutation": { + "updateMsSerivce": { + "file": "/home/joel/projects/open-source/jsonql/packages/koa/tests/fixtures/sub/resolver/mutation/update-ms-serivce.js", + "description": "create a mutation to test why the call said the payload already declared", + "params": [ + { + "type": [ + "string" + ], + "name": "payload", + "description": "incoming" + } + ], + "returns": [ + { + "type": [ + "string" + ], + "description": "output" + } + ] + } + }, + "auth": {}, + "timestamp": 1566213707037, + "sourceType": "script" +} diff --git a/packages/koa/tests/fixtures/sub/contract/public-contract.json b/packages/koa/tests/fixtures/sub/contract/public-contract.json new file mode 100644 index 0000000000000000000000000000000000000000..85559afe3fcd71111ea6c83ec5a1a0c16ea03126 --- /dev/null +++ b/packages/koa/tests/fixtures/sub/contract/public-contract.json @@ -0,0 +1,58 @@ +{ + "query": { + "helloWorld": { + "description": "This is the stock resolver for testing purpose", + "params": [], + "returns": [ + { + "type": "string", + "description": "stock message" + } + ] + }, + "msService": { + "description": false, + "params": [ + { + "type": [ + "string" + ], + "name": "msg", + "description": "incoming message" + } + ], + "returns": [ + { + "type": [ + "string" + ], + "description": "out going message" + } + ] + } + }, + "mutation": { + "updateMsSerivce": { + "description": "create a mutation to test why the call said the payload already declared", + "params": [ + { + "type": [ + "string" + ], + "name": "payload", + "description": "incoming" + } + ], + "returns": [ + { + "type": [ + "string" + ], + "description": "output" + } + ] + } + }, + "auth": {}, + "timestamp": 1566213707037 +} diff --git a/packages/koa/tests/fixtures/sub/resolver/mutation/update-ms-service.js b/packages/koa/tests/fixtures/sub/resolver/mutation/update-ms-service.js new file mode 100644 index 0000000000000000000000000000000000000000..d53bd1b0aacc946daa5ea819cb4782fa6144a186 --- /dev/null +++ b/packages/koa/tests/fixtures/sub/resolver/mutation/update-ms-service.js @@ -0,0 +1,8 @@ +/** + * create a mutation to test why the call said the payload already declared + * @param {string} payload incoming + * @return {string} output + */ +module.exports = function updateMsService(payload) { + return payload + ' updated'; +} diff --git a/packages/koa/tests/fixtures/sub/resolver/query/ms-service.js b/packages/koa/tests/fixtures/sub/resolver/query/ms-service.js new file mode 100644 index 0000000000000000000000000000000000000000..460f4e9a5e66d5754a980870aa10ea0946f7e78a --- /dev/null +++ b/packages/koa/tests/fixtures/sub/resolver/query/ms-service.js @@ -0,0 +1,11 @@ +const debug = require('debug')('jsonql-koa:query:ms-service') +/** + * @param {string} msg incoming message + * @return {string} out going message + */ +module.exports = function msService(msg) { + + debug('msg', msg) + + return msg + ' ms service'; +} diff --git a/packages/koa/tests/helpers/hello.js b/packages/koa/tests/helpers/hello.js new file mode 100644 index 0000000000000000000000000000000000000000..462b32e6e4d8fbee2727fe6c5a6323c2cbb9623d --- /dev/null +++ b/packages/koa/tests/helpers/hello.js @@ -0,0 +1,14 @@ +// wrapper function to test the server is running or not +const superkoa = require('superkoa') +const { headers } = require('../fixtures/options') +// export +module.exports = function hello(app) { + return superkoa(app) + .post('/jsonql') + .set(headers) + .send({ + helloWorld: { + args: [] + } + }); +} diff --git a/packages/koa/tests/helpers/server.js b/packages/koa/tests/helpers/server.js index 7e95b1ba5d856f8858a24f7207844cbfb833e315..166a8850e9c3420a2ad1bd3330e48462e537ce3f 100755 --- a/packages/koa/tests/helpers/server.js +++ b/packages/koa/tests/helpers/server.js @@ -14,8 +14,7 @@ module.exports = (config={}, dir = '') => { app.use(jsonqlMiddleware( Object.assign({},{ resolverDir: dirs.resolverDir, - contractDir: join(dirs.contractDir, dir), - useDoc: true + contractDir: join(dirs.contractDir, dir) }, config) )); return app; diff --git a/packages/koa/tests/node-client.test.js b/packages/koa/tests/node-client.test.js new file mode 100644 index 0000000000000000000000000000000000000000..4d50ac4cc888d196f3b8f084f4851aba7c880783 --- /dev/null +++ b/packages/koa/tests/node-client.test.js @@ -0,0 +1,78 @@ +// testing the ms feature +const test = require('ava') +const { join } = require('path') +const fsx = require('fs-extra') +const debug = require('debug')('jsonql-koa:test:node-client') +const nodeClient = require('jsonql-node-client') +const serverIoCore = require('server-io-core') +// setup +const jsonqlKoa = require('../') +const hello = require('./helpers/hello') +const baseDir = join(__dirname, 'fixtures') +const msPort = 6001; +const clientContractDir = join(__dirname, 'fixtures', 'tmp', 'client6002') +const createServer = require('./helpers/server') +const dir = 'server6002'; +// base test setup +test.before(async t => { + + t.context.baseApp = createServer({ + clientConfig: [{ + hostname: 'http://localhost:6002', + name: 'client0' + }] + }, dir) + t.context.baseServer = t.context.baseApp.listen(6002) + + const { app, stop } = serverIoCore({ + webroot: join(baseDir, 'html'), + socket:false, + open:false, + debugger: false, + port: msPort, + middlewares: [ + jsonqlKoa({ + contractDir: join(baseDir, 'sub', 'contract'), + resolverDir: join(baseDir, 'sub', 'resolver') + }) + ] + }) + t.context.app = app + t.context.stop = stop +}) + +test.after(t => { + t.context.stop() + t.context.baseServer.close() + // fsx.removeSync(clientContractDir) + // fsx.removeSync(join(baseDir, 'tmp', dir)) +}) + +test(`First test both server is running`, async t => { + const res1 = await hello(t.context.baseApp) + t.is(res1.status, 200) + const res2 = await hello(t.context.app) + t.is(res2.status, 200) +}) + +test.only(`It should able to call a resolver that access another ms`, async t => { + + const client = await nodeClient({ + hostname: 'http://localhost:6001', + contractDir: join(__dirname, 'fixtures', 'tmp', 'client6001') + }) + + const result = await client.mutation.updateMsSerivce('testing') + + /* + const client = await nodeClient({ + hostname: 'http://localhost:6002', + contractDir: clientContractDir + }) + // debug(client) + const result = await client.mutation.updateMsService('testing') + + */ + + t.truthy(result.indexOf(`ms service`)) +}) diff --git a/packages/node-client/package.json b/packages/node-client/package.json index 44b99fa07910634e6415cec5e5d6477db65695d2..95cbc78ca6f91b0cc8578a8764bad344a7e40856 100755 --- a/packages/node-client/package.json +++ b/packages/node-client/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-node-client", - "version": "1.1.5", + "version": "1.1.6", "description": "jsonql node.js client using request", "main": "index.js", "scripts": { @@ -35,15 +35,15 @@ "fs-extra": "^8.1.0", "jsonql-constants": "^1.7.9", "jsonql-contract": "^1.7.7", - "jsonql-errors": "^1.1.1", + "jsonql-errors": "^1.1.2", "jsonql-jwt": "^1.2.5", - "jsonql-params-validator": "^1.4.3", + "jsonql-params-validator": "^1.4.4", "lodash.merge": "^4.6.2", "node-cache": "^4.2.1", "request": "^2.88.0" }, "devDependencies": { - "ava": "^2.2.0", + "ava": "^2.3.0", "jsonql-koa": "^1.3.7", "nyc": "^14.1.1", "server-io-core": "^1.2.0" diff --git a/packages/node-client/src/check-options.js b/packages/node-client/src/check-options.js index 67afb0192c47358a0eff6bcba54b80b7b2987210..1fc942daaa2d3a8bc7675cfb44aff57ba7ee7589 100755 --- a/packages/node-client/src/check-options.js +++ b/packages/node-client/src/check-options.js @@ -5,7 +5,8 @@ const { createConfig, checkConfigAsync } = require('jsonql-params-validator') - +const { getDebug } = require('./utils') +const debug = getDebug('check-options') const { JSONQL_PATH, CONTENT_TYPE, @@ -70,6 +71,7 @@ const appProps = { // export just one method module.exports = function(config) { let { contract } = config; + debug(`jsonql-node-client raw config`, config) return checkConfigAsync(config, appProps, constProps) .then(opts => { opts.contract = contract; diff --git a/packages/node-client/src/generator.js b/packages/node-client/src/generator.js index d0966a29a2723583086187be8a069849b36f4771..13d3d0d24350de5ec5b6b71f85bbcb241a332eaa 100755 --- a/packages/node-client/src/generator.js +++ b/packages/node-client/src/generator.js @@ -52,8 +52,8 @@ const generator = (jsonqlInstance, config, contract) => { // generate the query method obj.query[queryFn] = (...args) => { const params = contract.query[queryFn].params; - const _args = params.map((param, i) => args[i]); - debug('query', queryFn, _args); + const _args = params.map((param, i) => args[i]) + debug('query', queryFn, _args) // the +1 parameter is the extra headers we want to pass const header = args[params.length] || {}; // hook the validateAsync into the chain diff --git a/packages/node-client/src/jsonql/request-client.js b/packages/node-client/src/jsonql/request-client.js index ffc5c01d2fe11c262b1aa913f606fca7a8fb4c71..4d7220cabc05fa311c945016c9d58366ecc60245 100755 --- a/packages/node-client/src/jsonql/request-client.js +++ b/packages/node-client/src/jsonql/request-client.js @@ -88,8 +88,8 @@ class JsonqlRequestClient extends JsonqlClient { * @api public */ mutation(name, payload={}, conditions={}, headers={}) { - const payload = createMutation(name, payload, conditions) - return this.__requestWrapper(PUT, payload, headers) + let _payload = createMutation(name, payload, conditions) + return this.__requestWrapper(PUT, _payload, headers) .then(clientErrorsHandler) .then(resultHandler) } diff --git a/packages/node-client/tests/fixtures/resolvers/mutation/send-user.js b/packages/node-client/tests/fixtures/resolvers/mutation/send-user.js index cf72fe87179c13c2a71da4aa5f7698dd5c65e21f..4f66baf14facba347b278c7899e7abc91d5a5d08 100755 --- a/packages/node-client/tests/fixtures/resolvers/mutation/send-user.js +++ b/packages/node-client/tests/fixtures/resolvers/mutation/send-user.js @@ -6,5 +6,5 @@ const merge = require('lodash.merge'); * @return {object} two merge together */ module.exports = function sendUser(payload, condition) { - return merge({timestamp: Date.now()}, payload, condition); + return merge({timestamp: Date.now()}, payload, condition) } diff --git a/packages/node-client/tests/main.test.js b/packages/node-client/tests/main.test.js index fba89ae4b339bbafcd78b97353cf131388442cea..183a9390b51ea34f9dccfad51c7db105518f72b6 100755 --- a/packages/node-client/tests/main.test.js +++ b/packages/node-client/tests/main.test.js @@ -26,3 +26,11 @@ test('Should able to say Hello world!' , async t => { const result = await t.context.client.query.helloWorld() t.is('Hello world!', result) }) + +test(`It should able to access the mutation call`, async t => { + + const result = await t.context.client.mutation.sendUser({name: 'Joel'}, {id: 1}) + + t.truthy(result.timestamp) + +}) diff --git a/packages/resolver/index.js b/packages/resolver/index.js index e98a3cabcd11eb883365ed5b70c184c943e8b8a8..4a6096c93c0a74bcdbc94b11603b937feefbb68b 100644 --- a/packages/resolver/index.js +++ b/packages/resolver/index.js @@ -7,7 +7,7 @@ const { const { getLocalValidator, handleAuthMethods -}= require('./src/handle-auth-methods') +} = require('./src/handle-auth-methods') // @TODO use the same for the jsonql-ws-server as well module.exports = { diff --git a/packages/resolver/package.json b/packages/resolver/package.json index b78bb76fe2003f2eb77fca574cca36dc4d7eac7b..5331838cb183d7571926865ed6d745aa088c78b2 100644 --- a/packages/resolver/package.json +++ b/packages/resolver/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-resolver", - "version": "0.5.0", + "version": "0.6.2", "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": [ @@ -9,7 +9,7 @@ ], "scripts": { "test": "ava --verbose", - "test:clients": "DEBUG=jsonql-resolver* ava --verbose ./tests/clients.test.js", + "test:clients": "DEBUG=jsonql* ava --verbose ./tests/clients.test.js", "contract": "jsonql-contract create ./tests/fixtures/resolvers ./tests/fixtures/contract" }, "keywords": [ @@ -20,14 +20,14 @@ "dependencies": { "debug": "^4.1.1", "jsonql-constants": "^1.7.9", - "jsonql-errors": "^1.1.1", + "jsonql-errors": "^1.1.2", "jsonql-jwt": "^1.2.5", - "jsonql-node-client": "^1.1.4", - "jsonql-params-validator": "^1.4.3", + "jsonql-node-client": "^1.1.5", + "jsonql-params-validator": "^1.4.4", "lodash.merge": "^4.6.2" }, "devDependencies": { - "ava": "^2.2.0", + "ava": "^2.3.0", "jsonql-contract": "^1.7.7", "jsonql-koa": "^1.3.7", "server-io-core": "^1.2.0" diff --git a/packages/resolver/src/client/validate-client-config.js b/packages/resolver/src/client/validate-client-config.js index eca0d2cad81da116a713612f0f1bf52438654c76..bed7e877e953f8579d720f91e21183849341f7ed 100644 --- a/packages/resolver/src/client/validate-client-config.js +++ b/packages/resolver/src/client/validate-client-config.js @@ -7,7 +7,7 @@ const debug = getDebug('validate-client-config') * @return {object|boolean} false when there is none, with additional properties */ const validateClientConfig = function(config) { - const ctn = config.clientConfig.length; + const ctn = config.clientConfig ? config.clientConfig.length : 0; // take the contractDir from the main const contractDir = config.contractDir; if (ctn) { @@ -27,7 +27,8 @@ const validateClientConfig = function(config) { } names.push(client.name) // next we need to create contract dir path using the name - clients.contractDir = join(contractDir, client.name) + client.contractDir = join(contractDir, client.name) + // push it back to the config clients.push(client) } return clients; diff --git a/packages/resolver/src/validate-and-call.js b/packages/resolver/src/validate-and-call.js index 97f89a69fe830057ab5fd9d874de659c41b8dd5d..6562564aba45417ec082e61d3931159d5c31c780 100644 --- a/packages/resolver/src/validate-and-call.js +++ b/packages/resolver/src/validate-and-call.js @@ -55,6 +55,7 @@ module.exports = function validateAndCall(fn, args, contract, type, name, opts) const { params } = extractParamsFromContract(contract, type, name) let errors = validateSync(args, params) if (errors.length) { + debug(`validation failed on client side`, args, params) throw new JsonqlValidationError(name, errors) } return Promise.resolve(fn.apply(null, args)) diff --git a/packages/resolver/tests/clients.test.js b/packages/resolver/tests/clients.test.js index 011043d73bca06884a9a06c2817106bd09c587fe..a2275c750835e50923d0a6c323440c0d2d300fb2 100644 --- a/packages/resolver/tests/clients.test.js +++ b/packages/resolver/tests/clients.test.js @@ -9,28 +9,27 @@ const { executeResolver } = require('../') const readJson = require('./fixtures/read-json') const { createQuery } = require('jsonql-params-validator') const baseDir = join(__dirname, 'fixtures') - +const { rmdirs } = require('./fixtures/rm') const contractPath = join(baseDir, 'contract', 'contract.json') test.before(async t => { const { stop, app } = anotherServer() t.context.stop = stop t.context.app = app - t.context.clientConfig = { hostname: 'http://localhost:8001' } - t.context.contract = await readJson(contractPath) t.context.opts = { resolverDir: join(baseDir, 'resolvers'), contractDir: join(baseDir, 'contract') } - }) test.after(t => { t.context.stop() + // remove the client contract , because that's part of the test + rmdirs(join(baseDir, 'contract', 'nodeClient0')) }) test(`Just testing the filter / reduce method`, t => { diff --git a/packages/resolver/tests/fixtures/rm.js b/packages/resolver/tests/fixtures/rm.js new file mode 100644 index 0000000000000000000000000000000000000000..09a68db1af27cc54ca41a3d7fbb5e267fe7acb55 --- /dev/null +++ b/packages/resolver/tests/fixtures/rm.js @@ -0,0 +1,32 @@ +// from https://stackoverflow.com/questions/18052762/remove-directory-which-is-not-empty +const fs = require('fs'); +const path = require('path'); +const { promisify } = require('util'); +const readdir = promisify(fs.readdir); +const rmdir = promisify(fs.rmdir); +const unlink = promisify(fs.unlink); + +/* +exports.rmdirs = async function rmdirs(dir) { + let entries = await readdir(dir, { withFileTypes: true }); + await Promise.all(entries.map(entry => { + let fullPath = path.join(dir, entry.name); + return entry.isDirectory() ? rmdirs(fullPath) : unlink(fullPath); + })); + await rmdir(dir); +}; +*/ + +exports.rmdirs = async function rmdirs(dir) { + let entries = await readdir(dir, { withFileTypes: true }); + let results = await Promise.all(entries.map(entry => { + let fullPath = path.join(dir, entry.name); + let task = entry.isDirectory() ? rmdirs(fullPath) : unlink(fullPath); + return task.catch(error => ({ error })); + })); + results.forEach(result => { + // Ignore missing files/directories; bail on other errors + if (result && result.error.code !== 'ENOENT') throw result.error; + }); + await rmdir(dir); +}; diff --git a/packages/validator/dist/jsonql-params-validator.cjs.js b/packages/validator/dist/jsonql-params-validator.cjs.js index 32ccd036e76941941b2b9158bad8e524744792b7..c4e50fb09c91cda4400efdeaaf931fac85519be1 100644 --- a/packages/validator/dist/jsonql-params-validator.cjs.js +++ b/packages/validator/dist/jsonql-params-validator.cjs.js @@ -1,2 +1,2 @@ -"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},freeGlobal="object"==typeof global$1&&global$1&&global$1.Object===Object&&global$1,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag=Symbol?Symbol.toStringTag:void 0;function getRawTag(e){var r=hasOwnProperty.call(e,symToStringTag),t=e[symToStringTag];try{var a=!(e[symToStringTag]=void 0)}catch(e){}var n=nativeObjectToString.call(e);return a&&(r?e[symToStringTag]=t:delete e[symToStringTag]),n}var objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString;function objectToString(e){return nativeObjectToString$1.call(e)}var nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag$1=Symbol?Symbol.toStringTag:void 0;function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag$1&&symToStringTag$1 in Object(e)?getRawTag(e):objectToString(e)}function isObjectLike(e){return null!=e&&"object"==typeof e}var symbolTag="[object Symbol]";function isSymbol(e){return"symbol"==typeof e||isObjectLike(e)&&baseGetTag(e)==symbolTag}function arrayMap(e,r){for(var t=-1,a=null==e?0:e.length,n=Array(a);++t=HOT_COUNT)return arguments[0]}else a=0;return t.apply(void 0,arguments)}}function constant(e){return function(){return e}}var defineProperty=function(){try{var e=getNative(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),baseSetToString=defineProperty?function(e,r){return defineProperty(e,"toString",{configurable:!0,enumerable:!1,value:constant(r),writable:!0})}:identity,setToString=shortOut(baseSetToString);function baseFindIndex(e,r,t,a){for(var n=e.length,o=t+(a?1:-1);a?o--:++o>>0,r>>>=0;for(var o=Array(n);++a",NO_STATUS_CODE=-1,ARGS_NOT_ARRAY_ERR="args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)",PARAMS_NOT_ARRAY_ERR="params is not an array! Did something gone wrong when you generate the contract.json?",EXCEPTION_CASE_ERR="Could not understand your arguments and parameter structure!",DEFAULT_TYPE$1=DEFAULT_TYPE,ARRAY_TYPE_LFT$1=ARRAY_TYPE_LFT,ARRAY_TYPE_RGT$1=ARRAY_TYPE_RGT,TYPE_KEY$1=TYPE_KEY,OPTIONAL_KEY$1=OPTIONAL_KEY,ENUM_KEY$1=ENUM_KEY,ARGS_KEY$1=ARGS_KEY,CHECKER_KEY$1=CHECKER_KEY,ALIAS_KEY$1=ALIAS_KEY,ARRAY_TYPE$1=ARRAY_TYPE,OBJECT_TYPE$1=OBJECT_TYPE,STRING_TYPE$1=STRING_TYPE,BOOLEAN_TYPE$1=BOOLEAN_TYPE,NUMBER_TYPE$1=NUMBER_TYPE,KEY_WORD$1=KEY_WORD,OR_SEPERATOR$1=OR_SEPERATOR,combineFn=function(e){switch(e){case NUMBER_TYPE$1:return checkIsNumber;case STRING_TYPE$1:return checkIsString;case BOOLEAN_TYPE$1:return checkIsBoolean;default:return checkIsAny}},checkIsArray=function(e,r){return void 0===r&&(r=""),!!isArray(e)&&(""===r||""===trim(r)||!(0t.filter(function(e){return!combineFn(e)(r)}).length)}).length:t.length>t.filter(function(e){return!checkIsArray(r,e)}).length},checkIsObject=function(r,e){if(void 0===e&&(e=null),isPlainObject(r)){if(!e)return!0;if(checkIsArray(e))return!e.filter(function(e){var t=r[e.name];return!(e.type.length>e.type.filter(function(e){var r;return!!isUndefined(t)||(!1!==(r=isArrayLike$1(e))?!arrayTypeHandler({arg:t},r):!combineFn(e)(t))}).length)}).length}return!1},objectTypeHandler=function(e){var r=e.arg,t=e.param,a=[r];return Array.isArray(t.keys)&&t.keys.length&&a.push(t.keys),checkIsObject.apply(null,a)},JsonqlEnumError=function(t){function a(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=a.name,t.captureStackTrace&&t.captureStackTrace(this,a)}t&&(a.__proto__=t),(a.prototype=Object.create(t&&t.prototype)).constructor=a;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(a,e),a}(Error),JsonqlTypeError=function(t){function a(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=a.name,t.captureStackTrace&&t.captureStackTrace(this,a)}t&&(a.__proto__=t),(a.prototype=Object.create(t&&t.prototype)).constructor=a;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(a,e),a}(Error),JsonqlCheckerError=function(t){function a(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=a.name,t.captureStackTrace&&t.captureStackTrace(this,a)}t&&(a.__proto__=t),(a.prototype=Object.create(t&&t.prototype)).constructor=a;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(a,e),a}(Error),JsonqlValidationError=function(t){function a(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=a.name,t.captureStackTrace&&t.captureStackTrace(this,a)}t&&(a.__proto__=t),(a.prototype=Object.create(t&&t.prototype)).constructor=a;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(a,e),a}(Error),JsonqlError=function(t){function a(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=a.name,t.captureStackTrace&&t.captureStackTrace(this,a)}t&&(a.__proto__=t),(a.prototype=Object.create(t&&t.prototype)).constructor=a;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return NO_STATUS_CODE},Object.defineProperties(a,e),a}(Error),optionalHandler=function(r){var e=r.arg,t=r.param;return!!notEmpty(e)&&!(t.type.length>t.type.filter(function(e){return validateHandler(e,r)}).length)},validateHandler=function(e,r){var t;switch(!0){case e===OBJECT_TYPE$1:return!objectTypeHandler(r);case e===ARRAY_TYPE$1:return!checkIsArray(r.arg);case!1!==(t=isArrayLike$1(e)):return!arrayTypeHandler(r,t);default:return!combineFn(e)(r.arg)}},getOptionalValue=function(e,r){return isUndefined(e)?!0!==r.optional||isUndefined(r.defaultvalue)?null:r.defaultvalue:e},normalizeArgs=function(t,a){if(!checkIsArray(a))throw new JsonqlError(PARAMS_NOT_ARRAY_ERR);if(0===a.length)return[];if(!checkIsArray(t))throw new JsonqlError(ARGS_NOT_ARRAY_ERR);switch(!0){case t.length==a.length:return t.map(function(e,r){return{arg:e,index:r,param:a[r]}});case!0===a[0].variable:var n=a[0].type;return t.map(function(e,r){return{arg:e,index:r,param:a[r]||{type:n,name:"_"}}});case t.lengtha.length&&1===a.length:var e,o=[DEFAULT_TYPE$1];return!1!==(e=isArrayLike$1(a[0].type[0]))&&(o=e),t.map(function(e,r){return{arg:e,index:r,param:a[r]||{type:o,name:"_"}}});default:throw new JsonqlError(EXCEPTION_CASE_ERR,{args:t,params:a})}},processReturn=function(e){return e.map(function(e){return e.arg})},validateSync=function(e,r,t){var a;void 0===t&&(t=!1);var n=normalizeArgs(e,r),o=n.filter(function(r){return!0===r.param.optional?optionalHandler(r):!(r.param.type.length>r.param.type.filter(function(e){return validateHandler(e,r)}).length)});return t?((a={})[ERROR_KEY]=o,a[DATA_KEY]=processReturn(n),a):o},validateAsync=function(a,n,o){return void 0===o&&(o=!1),new Promise(function(e,r){var t=validateSync(a,n,o);return o?t[ERROR_KEY].length?r(t[ERROR_KEY]):e(t[DATA_KEY]):t.length?r(t):e([])})},isInArray=function(e,r){return!!e.filter(function(e){return e===r}).length},checkKeyInObject=function(e,r){var t=Object.keys(e);return isInArray(t,r)},isEmpty=function(e){return!notEmpty(e)};function mapAliasConfigKeys(e,r){var t=omitBy(r,function(e,r){return!e[ALIAS_KEY$1]});return isEqual(t,{})?e:mapKeys(e,function(e,r){return findKey(t,function(e){return e.alias===r})||r})}function preservePristineValues(e,r){var t=mapAliasConfigKeys(e,r);return{pristineValues:mapValues(omitBy(r,function(e,r){return checkKeyInObject(t,r)}),function(e){return e.args}),checkAgainstAppProps:omitBy(r,function(e,r){return!checkKeyInObject(t,r)}),config:t}}function processConfigAction(n,e){return mapValues(e,function(e,r){var t,a;return isUndefined(n[r])||!0===e[OPTIONAL_KEY$1]&&isEmpty(n[r])?merge({},e,((t={})[KEY_WORD$1]=!0,t)):((a={})[ARGS_KEY$1]=n[r],a[TYPE_KEY$1]=e[TYPE_KEY$1],a[OPTIONAL_KEY$1]=e[OPTIONAL_KEY$1]||!1,a[ENUM_KEY$1]=e[ENUM_KEY$1]||!1,a[CHECKER_KEY$1]=e[CHECKER_KEY$1]||!1,a)})}function prepareArgsForValidation(e,r){var t=preservePristineValues(e,r),a=t.config,n=t.pristineValues;return[processConfigAction(a,t.checkAgainstAppProps),n]}var toArray=function(e){return checkIsArray(e)?e:[e]},inArray=function(e,r){return!!e.filter(function(e){return e===r}).length};function validateHandler$1(e,r){var t,a=[[e[ARGS_KEY$1]],[(t={},t[TYPE_KEY$1]=toArray(e[TYPE_KEY$1]),t[OPTIONAL_KEY$1]=e[OPTIONAL_KEY$1],t)]];return Reflect.apply(r,null,a)}var enumHandler=function(e,r){return!checkIsArray(r)||inArray(r,e)},checkerHandler=function(e,r){try{return!!isFunction(r)&&r.apply(null,[e])}catch(e){return!1}};function runValidationAction(a){return function(e,r){if(e[KEY_WORD$1])return e[ARGS_KEY$1];var t=validateHandler$1(e,a);if(t.length)throw new JsonqlTypeError(r,t);if(!1!==e[ENUM_KEY$1]&&!enumHandler(e[ARGS_KEY$1],e[ENUM_KEY$1]))throw new JsonqlEnumError(r);if(!1!==e[CHECKER_KEY$1]&&!checkerHandler(e[ARGS_KEY$1],e[CHECKER_KEY$1]))throw new JsonqlCheckerError(r);return e[ARGS_KEY$1]}}function runValidation(e,r){var t=e[0],a=e[1],n=mapValues(t,runValidationAction(r));return merge(n,a)}var configToArgs=function(e,r){return Promise.resolve(prepareArgsForValidation(e,r))};function checkOptionsAsync(e,r,t,a){return void 0===e&&(e={}),configToArgs(e,r).then(function(e){return runValidation(e,a)}).then(function(e){return merge({},e,t)})}function checkOptionsSync(e,r,t,a){return void 0===e&&(e={}),merge(runValidation(prepareArgsForValidation(e,r),a),t)}function constructConfigFn(e,r,t,a,n,o){void 0===t&&(t=!1),void 0===a&&(a=!1),void 0===n&&(n=!1),void 0===o&&(o=!1);var i={};return i[ARGS_KEY]=e,i[TYPE_KEY]=r,!0===t&&(i[OPTIONAL_KEY]=!0),checkIsArray(a)&&(i[ENUM_KEY]=a),isFunction(n)&&(i[CHECKER_KEY]=n),isString(o)&&(i[ALIAS_KEY]=o),i}var createConfig=function(e,r,t){void 0===t&&(t={});var a=t[OPTIONAL_KEY],n=t[ENUM_KEY],o=t[CHECKER_KEY],i=t[ALIAS_KEY];return constructConfigFn.apply(null,[e,r,a,n,o,i])},JSONQL_PARAMS_VALIDATOR_INFO="version: 1.4.3 module: cjs",checkConfigAsync=function(a){return function(e,r,t){return void 0===t&&(t={}),checkOptionsAsync(e,r,t,a)}},checkConfig=function(a){return function(e,r,t){return void 0===t&&(t={}),checkOptionsSync(e,r,t,a)}};function checkIsContract(e){return checkIsObject(e)&&(checkKeyInObject(e,QUERY_NAME)||checkKeyInObject(e,MUTATION_NAME)||checkKeyInObject(e,SOCKET_NAME))}var formatPayload=function(e){return checkIsString(e)?JSON.parse(e):e};function getNameFromPayload(e){return Object.keys(e)[0]}function createQuery(e,r,t){var a;if(void 0===r&&(r=[]),void 0===t&&(t=!1),checkIsString(e)&&checkIsArray(r)){var n={};return n[QUERY_ARG_NAME]=r,!0===t?n:((a={})[e]=n,a)}throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!",{resolverName:e,args:r})}function createQueryStr(e,r,t){return void 0===r&&(r=[]),void 0===t&&(t=!1),JSON.stringify(createQuery(e,r,t))}function createMutation(e,r,t,a){var n;void 0===t&&(t={}),void 0===a&&(a=!1);var o={};if(o[PAYLOAD_PARAM_NAME]=r,o[CONDITION_PARAM_NAME]=t,!0===a)return o;if(checkIsString(e))return(n={})[e]=o,n;throw new JsonqlValidationError("[createMutation] expect resolverName to be string!",{resolverName:e,payload:r,condition:t})}function createMutationStr(e,r,t,a){return void 0===t&&(t={}),void 0===a&&(a=!1),JSON.stringify(createMutation(e,r,t,a))}function getQueryFromArgs(e,r){var t;if(e&&checkIsObject(r)){var a=r[e];if(a[QUERY_ARG_NAME])return(t={})[RESOLVER_PARAM_NAME]=e,t[QUERY_ARG_NAME]=a[QUERY_ARG_NAME],t}return!1}function getQueryFromPayload(e){var r=formatPayload(e),t=getQueryFromArgs(getNameFromPayload(r),r);if(!1!==t)return t;throw new JsonqlValidationError("[getQueryArgs] Payload is malformed!",e)}function getMutationFromArgs(e,r){var t;if(e&&checkIsObject(r)){var a=r[e];if(a)return(t={})[RESOLVER_PARAM_NAME]=e,t[PAYLOAD_PARAM_NAME]=a[PAYLOAD_PARAM_NAME],t[CONDITION_PARAM_NAME]=a[CONDITION_PARAM_NAME],t}return!1}function getMutationFromPayload(e){var r=formatPayload(e),t=getMutationFromArgs(getNameFromPayload(r),r);if(!1!==t)return t;throw new JsonqlValidationError("[getMutationArgs] Payload is malformed!",e)}var isObject$1=checkIsObject,isAny=checkIsAny,isString$1=checkIsString,isBoolean$1=checkIsBoolean,isNumber$1=checkIsNumber,isArray$1=checkIsArray,isNotEmpty=notEmpty,normalizeArgs$1=normalizeArgs,validateSync$1=validateSync,validateAsync$1=validateAsync,JSONQL_PARAMS_VALIDATOR_INFO$1=JSONQL_PARAMS_VALIDATOR_INFO,createConfig$1=createConfig,constructConfig=constructConfigFn,checkConfigAsync$1=checkConfigAsync(validateSync),checkConfig$1=checkConfig(validateSync),inArray$1=isInArray,isKeyInObject=checkKeyInObject,isContract=checkIsContract,createQuery$1=createQuery,createQueryStr$1=createQueryStr,createMutation$1=createMutation,createMutationStr$1=createMutationStr,getQueryFromArgs$1=getQueryFromArgs,getQueryFromPayload$1=getQueryFromPayload,getMutationFromArgs$1=getMutationFromArgs,getMutationFromPayload$1=getMutationFromPayload,getNameFromPayload$1=getNameFromPayload;exports.JSONQL_PARAMS_VALIDATOR_INFO=JSONQL_PARAMS_VALIDATOR_INFO$1,exports.checkConfig=checkConfig$1,exports.checkConfigAsync=checkConfigAsync$1,exports.constructConfig=constructConfig,exports.createConfig=createConfig$1,exports.createMutation=createMutation$1,exports.createMutationStr=createMutationStr$1,exports.createQuery=createQuery$1,exports.createQueryStr=createQueryStr$1,exports.getMutationFromArgs=getMutationFromArgs$1,exports.getMutationFromPayload=getMutationFromPayload$1,exports.getNameFromPayload=getNameFromPayload$1,exports.getQueryFromArgs=getQueryFromArgs$1,exports.getQueryFromPayload=getQueryFromPayload$1,exports.inArray=inArray$1,exports.isAny=isAny,exports.isArray=isArray$1,exports.isBoolean=isBoolean$1,exports.isContract=isContract,exports.isKeyInObject=isKeyInObject,exports.isNotEmpty=isNotEmpty,exports.isNumber=isNumber$1,exports.isObject=isObject$1,exports.isString=isString$1,exports.normalizeArgs=normalizeArgs$1,exports.validateAsync=validateAsync$1,exports.validateSync=validateSync$1; +"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},freeGlobal="object"==typeof global$1&&global$1&&global$1.Object===Object&&global$1,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag=Symbol?Symbol.toStringTag:void 0;function getRawTag(e){var r=hasOwnProperty.call(e,symToStringTag),t=e[symToStringTag];try{var a=!(e[symToStringTag]=void 0)}catch(e){}var n=nativeObjectToString.call(e);return a&&(r?e[symToStringTag]=t:delete e[symToStringTag]),n}var objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString;function objectToString(e){return nativeObjectToString$1.call(e)}var nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag$1=Symbol?Symbol.toStringTag:void 0;function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag$1&&symToStringTag$1 in Object(e)?getRawTag(e):objectToString(e)}function isObjectLike(e){return null!=e&&"object"==typeof e}var symbolTag="[object Symbol]";function isSymbol(e){return"symbol"==typeof e||isObjectLike(e)&&baseGetTag(e)==symbolTag}function arrayMap(e,r){for(var t=-1,a=null==e?0:e.length,n=Array(a);++t=HOT_COUNT)return arguments[0]}else a=0;return t.apply(void 0,arguments)}}function constant(e){return function(){return e}}var defineProperty=function(){try{var e=getNative(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),baseSetToString=defineProperty?function(e,r){return defineProperty(e,"toString",{configurable:!0,enumerable:!1,value:constant(r),writable:!0})}:identity,setToString=shortOut(baseSetToString);function baseFindIndex(e,r,t,a){for(var n=e.length,o=t+(a?1:-1);a?o--:++o>>0,r>>>=0;for(var o=Array(n);++a",NO_STATUS_CODE=-1,ARGS_NOT_ARRAY_ERR="args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)",PARAMS_NOT_ARRAY_ERR="params is not an array! Did something gone wrong when you generate the contract.json?",EXCEPTION_CASE_ERR="Could not understand your arguments and parameter structure!",DEFAULT_TYPE$1=DEFAULT_TYPE,ARRAY_TYPE_LFT$1=ARRAY_TYPE_LFT,ARRAY_TYPE_RGT$1=ARRAY_TYPE_RGT,TYPE_KEY$1=TYPE_KEY,OPTIONAL_KEY$1=OPTIONAL_KEY,ENUM_KEY$1=ENUM_KEY,ARGS_KEY$1=ARGS_KEY,CHECKER_KEY$1=CHECKER_KEY,ALIAS_KEY$1=ALIAS_KEY,ARRAY_TYPE$1=ARRAY_TYPE,OBJECT_TYPE$1=OBJECT_TYPE,STRING_TYPE$1=STRING_TYPE,BOOLEAN_TYPE$1=BOOLEAN_TYPE,NUMBER_TYPE$1=NUMBER_TYPE,KEY_WORD$1=KEY_WORD,OR_SEPERATOR$1=OR_SEPERATOR,combineFn=function(e){switch(e){case NUMBER_TYPE$1:return checkIsNumber;case STRING_TYPE$1:return checkIsString;case BOOLEAN_TYPE$1:return checkIsBoolean;default:return checkIsAny}},checkIsArray=function(e,r){return void 0===r&&(r=""),!!isArray(e)&&(""===r||""===trim(r)||!(0t.filter(function(e){return!combineFn(e)(r)}).length)}).length:t.length>t.filter(function(e){return!checkIsArray(r,e)}).length},checkIsObject=function(r,e){if(void 0===e&&(e=null),isPlainObject(r)){if(!e)return!0;if(checkIsArray(e))return!e.filter(function(e){var t=r[e.name];return!(e.type.length>e.type.filter(function(e){var r;return!!isUndefined(t)||(!1!==(r=isArrayLike$1(e))?!arrayTypeHandler({arg:t},r):!combineFn(e)(t))}).length)}).length}return!1},objectTypeHandler=function(e){var r=e.arg,t=e.param,a=[r];return Array.isArray(t.keys)&&t.keys.length&&a.push(t.keys),checkIsObject.apply(null,a)},isBrowser=function(){try{if(window||document)return!0}catch(e){}return!1},isNode=function(){try{if(!isBrowser()&&global$1)return!0}catch(e){}return!1};function whereAmI(){return isBrowser()?"browser":isNode()?"node":"unknown"}var JsonqlBaseError=function(t){function e(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];t.apply(this,e)}return t&&(e.__proto__=t),((e.prototype=Object.create(t&&t.prototype)).constructor=e).where=function(){return whereAmI()},e}(Error),JsonqlEnumError=function(t){function a(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=a.name,t.captureStackTrace&&t.captureStackTrace(this,a)}t&&(a.__proto__=t),(a.prototype=Object.create(t&&t.prototype)).constructor=a;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(a,e),a}(Error),JsonqlTypeError=function(t){function a(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=a.name,t.captureStackTrace&&t.captureStackTrace(this,a)}t&&(a.__proto__=t),(a.prototype=Object.create(t&&t.prototype)).constructor=a;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(a,e),a}(Error),JsonqlCheckerError=function(t){function a(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=a.name,t.captureStackTrace&&t.captureStackTrace(this,a)}t&&(a.__proto__=t),(a.prototype=Object.create(t&&t.prototype)).constructor=a;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(a,e),a}(Error),JsonqlValidationError=function(t){function a(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=a.name,Error.captureStackTrace&&Error.captureStackTrace(this,a)}t&&(a.__proto__=t),(a.prototype=Object.create(t&&t.prototype)).constructor=a;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(a,e),a}(JsonqlBaseError),JsonqlError=function(t){function a(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];t.apply(this,e),this.message=e[0],this.detail=e[1],this.className=a.name,Error.captureStackTrace&&Error.captureStackTrace(this,a)}t&&(a.__proto__=t),(a.prototype=Object.create(t&&t.prototype)).constructor=a;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return NO_STATUS_CODE},Object.defineProperties(a,e),a}(JsonqlBaseError);function log(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];try{window&&window.debug&&Reflect.apply(console.log,console,e)}catch(e){}}var optionalHandler=function(r){var e=r.arg,t=r.param;return!!notEmpty(e)&&!(t.type.length>t.type.filter(function(e){return validateHandler(e,r)}).length)},validateHandler=function(e,r){var t;switch(!0){case e===OBJECT_TYPE$1:return!objectTypeHandler(r);case e===ARRAY_TYPE$1:return!checkIsArray(r.arg);case!1!==(t=isArrayLike$1(e)):return!arrayTypeHandler(r,t);default:return!combineFn(e)(r.arg)}},getOptionalValue=function(e,r){return isUndefined(e)?!0!==r.optional||isUndefined(r.defaultvalue)?null:r.defaultvalue:e},normalizeArgs=function(t,n){if(!checkIsArray(n))throw new JsonqlError(PARAMS_NOT_ARRAY_ERR);if(0===n.length)return[];if(!checkIsArray(t))throw new JsonqlError(ARGS_NOT_ARRAY_ERR);switch(!0){case t.length==n.length:return log(1),t.map(function(e,r){return{arg:e,index:r,param:n[r]}});case!0===n[0].variable:log(2);var a=n[0].type;return t.map(function(e,r){return{arg:e,index:r,param:n[r]||{type:a,name:"_"}}});case t.lengthn.length:log(4);var o=n.length,i=[DEFAULT_TYPE$1];return t.map(function(e,r){var t=o<=r||!!n[r].optional,a=n[r]||{type:i,name:"_"+r};return{arg:t?getOptionalValue(e,a):e,index:r,param:a,optional:t}});default:throw log(5),new JsonqlError(EXCEPTION_CASE_ERR,{args:t,params:n})}},processReturn=function(e){return e.map(function(e){return e.arg})},validateSync=function(e,r,t){var a;void 0===t&&(t=!1);var n=normalizeArgs(e,r),o=n.filter(function(r){return!0===r.optional||!0===r.param.optional?optionalHandler(r):!(r.param.type.length>r.param.type.filter(function(e){return validateHandler(e,r)}).length)});return t?((a={})[ERROR_KEY]=o,a[DATA_KEY]=processReturn(n),a):o},validateAsync=function(a,n,o){return void 0===o&&(o=!1),new Promise(function(e,r){var t=validateSync(a,n,o);return o?t[ERROR_KEY].length?r(t[ERROR_KEY]):e(t[DATA_KEY]):t.length?r(t):e([])})},isInArray=function(e,r){return!!e.filter(function(e){return e===r}).length},checkKeyInObject=function(e,r){var t=Object.keys(e);return isInArray(t,r)},isEmpty=function(e){return!notEmpty(e)};function mapAliasConfigKeys(e,r){var t=omitBy(r,function(e,r){return!e[ALIAS_KEY$1]});return isEqual(t,{})?e:mapKeys(e,function(e,r){return findKey(t,function(e){return e.alias===r})||r})}function preservePristineValues(e,r){var t=mapAliasConfigKeys(e,r);return{pristineValues:mapValues(omitBy(r,function(e,r){return checkKeyInObject(t,r)}),function(e){return e.args}),checkAgainstAppProps:omitBy(r,function(e,r){return!checkKeyInObject(t,r)}),config:t}}function processConfigAction(n,e){return mapValues(e,function(e,r){var t,a;return isUndefined(n[r])||!0===e[OPTIONAL_KEY$1]&&isEmpty(n[r])?merge({},e,((t={})[KEY_WORD$1]=!0,t)):((a={})[ARGS_KEY$1]=n[r],a[TYPE_KEY$1]=e[TYPE_KEY$1],a[OPTIONAL_KEY$1]=e[OPTIONAL_KEY$1]||!1,a[ENUM_KEY$1]=e[ENUM_KEY$1]||!1,a[CHECKER_KEY$1]=e[CHECKER_KEY$1]||!1,a)})}function prepareArgsForValidation(e,r){var t=preservePristineValues(e,r),a=t.config,n=t.pristineValues;return[processConfigAction(a,t.checkAgainstAppProps),n]}var toArray=function(e){return checkIsArray(e)?e:[e]},inArray=function(e,r){return!!e.filter(function(e){return e===r}).length};function validateHandler$1(e,r){var t,a=[[e[ARGS_KEY$1]],[(t={},t[TYPE_KEY$1]=toArray(e[TYPE_KEY$1]),t[OPTIONAL_KEY$1]=e[OPTIONAL_KEY$1],t)]];return Reflect.apply(r,null,a)}var enumHandler=function(e,r){return!checkIsArray(r)||inArray(r,e)},checkerHandler=function(e,r){try{return!!isFunction(r)&&r.apply(null,[e])}catch(e){return!1}};function runValidationAction(a){return function(e,r){if(e[KEY_WORD$1])return e[ARGS_KEY$1];var t=validateHandler$1(e,a);if(t.length)throw log("runValidationAction",r,e),new JsonqlTypeError(r,t);if(!1!==e[ENUM_KEY$1]&&!enumHandler(e[ARGS_KEY$1],e[ENUM_KEY$1]))throw log(ENUM_KEY$1,e[ENUM_KEY$1]),new JsonqlEnumError(r);if(!1!==e[CHECKER_KEY$1]&&!checkerHandler(e[ARGS_KEY$1],e[CHECKER_KEY$1]))throw log(CHECKER_KEY$1,e[CHECKER_KEY$1]),new JsonqlCheckerError(r);return e[ARGS_KEY$1]}}function runValidation(e,r){var t=e[0],a=e[1],n=mapValues(t,runValidationAction(r));return merge(n,a)}var configToArgs=function(e,r){return Promise.resolve(prepareArgsForValidation(e,r))};function checkOptionsAsync(e,r,t,a){return void 0===e&&(e={}),configToArgs(e,r).then(function(e){return runValidation(e,a)}).then(function(e){return merge({},e,t)})}function checkOptionsSync(e,r,t,a){return void 0===e&&(e={}),merge(runValidation(prepareArgsForValidation(e,r),a),t)}function constructConfigFn(e,r,t,a,n,o){void 0===t&&(t=!1),void 0===a&&(a=!1),void 0===n&&(n=!1),void 0===o&&(o=!1);var i={};return i[ARGS_KEY]=e,i[TYPE_KEY]=r,!0===t&&(i[OPTIONAL_KEY]=!0),checkIsArray(a)&&(i[ENUM_KEY]=a),isFunction(n)&&(i[CHECKER_KEY]=n),isString(o)&&(i[ALIAS_KEY]=o),i}var createConfig=function(e,r,t){void 0===t&&(t={});var a=t[OPTIONAL_KEY],n=t[ENUM_KEY],o=t[CHECKER_KEY],i=t[ALIAS_KEY];return constructConfigFn.apply(null,[e,r,a,n,o,i])},JSONQL_PARAMS_VALIDATOR_INFO="version: 1.4.4 module: cjs",checkConfigAsync=function(a){return function(e,r,t){return void 0===t&&(t={}),checkOptionsAsync(e,r,t,a)}},checkConfig=function(a){return function(e,r,t){return void 0===t&&(t={}),checkOptionsSync(e,r,t,a)}};function checkIsContract(e){return checkIsObject(e)&&(checkKeyInObject(e,QUERY_NAME)||checkKeyInObject(e,MUTATION_NAME)||checkKeyInObject(e,SOCKET_NAME))}var formatPayload=function(e){return checkIsString(e)?JSON.parse(e):e};function getNameFromPayload(e){return Object.keys(e)[0]}function createQuery(e,r,t){var a;if(void 0===r&&(r=[]),void 0===t&&(t=!1),checkIsString(e)&&checkIsArray(r)){var n={};return n[QUERY_ARG_NAME]=r,!0===t?n:((a={})[e]=n,a)}throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!",{resolverName:e,args:r})}function createQueryStr(e,r,t){return void 0===r&&(r=[]),void 0===t&&(t=!1),JSON.stringify(createQuery(e,r,t))}function createMutation(e,r,t,a){var n;void 0===t&&(t={}),void 0===a&&(a=!1);var o={};if(o[PAYLOAD_PARAM_NAME]=r,o[CONDITION_PARAM_NAME]=t,!0===a)return o;if(checkIsString(e))return(n={})[e]=o,n;throw new JsonqlValidationError("[createMutation] expect resolverName to be string!",{resolverName:e,payload:r,condition:t})}function createMutationStr(e,r,t,a){return void 0===t&&(t={}),void 0===a&&(a=!1),JSON.stringify(createMutation(e,r,t,a))}function getQueryFromArgs(e,r){var t;if(e&&checkIsObject(r)){var a=r[e];if(a[QUERY_ARG_NAME])return(t={})[RESOLVER_PARAM_NAME]=e,t[QUERY_ARG_NAME]=a[QUERY_ARG_NAME],t}return!1}function getQueryFromPayload(e){var r=formatPayload(e),t=getQueryFromArgs(getNameFromPayload(r),r);if(!1!==t)return t;throw new JsonqlValidationError("[getQueryArgs] Payload is malformed!",e)}function getMutationFromArgs(e,r){var t;if(e&&checkIsObject(r)){var a=r[e];if(a)return(t={})[RESOLVER_PARAM_NAME]=e,t[PAYLOAD_PARAM_NAME]=a[PAYLOAD_PARAM_NAME],t[CONDITION_PARAM_NAME]=a[CONDITION_PARAM_NAME],t}return!1}function getMutationFromPayload(e){var r=formatPayload(e),t=getMutationFromArgs(getNameFromPayload(r),r);if(!1!==t)return t;throw new JsonqlValidationError("[getMutationArgs] Payload is malformed!",e)}var isObject$1=checkIsObject,isAny=checkIsAny,isString$1=checkIsString,isBoolean$1=checkIsBoolean,isNumber$1=checkIsNumber,isArray$1=checkIsArray,isNotEmpty=notEmpty,normalizeArgs$1=normalizeArgs,validateSync$1=validateSync,validateAsync$1=validateAsync,JSONQL_PARAMS_VALIDATOR_INFO$1=JSONQL_PARAMS_VALIDATOR_INFO,createConfig$1=createConfig,constructConfig=constructConfigFn,checkConfigAsync$1=checkConfigAsync(validateSync),checkConfig$1=checkConfig(validateSync),inArray$1=isInArray,isKeyInObject=checkKeyInObject,isContract=checkIsContract,createQuery$1=createQuery,createQueryStr$1=createQueryStr,createMutation$1=createMutation,createMutationStr$1=createMutationStr,getQueryFromArgs$1=getQueryFromArgs,getQueryFromPayload$1=getQueryFromPayload,getMutationFromArgs$1=getMutationFromArgs,getMutationFromPayload$1=getMutationFromPayload,getNameFromPayload$1=getNameFromPayload;exports.JSONQL_PARAMS_VALIDATOR_INFO=JSONQL_PARAMS_VALIDATOR_INFO$1,exports.checkConfig=checkConfig$1,exports.checkConfigAsync=checkConfigAsync$1,exports.constructConfig=constructConfig,exports.createConfig=createConfig$1,exports.createMutation=createMutation$1,exports.createMutationStr=createMutationStr$1,exports.createQuery=createQuery$1,exports.createQueryStr=createQueryStr$1,exports.getMutationFromArgs=getMutationFromArgs$1,exports.getMutationFromPayload=getMutationFromPayload$1,exports.getNameFromPayload=getNameFromPayload$1,exports.getQueryFromArgs=getQueryFromArgs$1,exports.getQueryFromPayload=getQueryFromPayload$1,exports.inArray=inArray$1,exports.isAny=isAny,exports.isArray=isArray$1,exports.isBoolean=isBoolean$1,exports.isContract=isContract,exports.isKeyInObject=isKeyInObject,exports.isNotEmpty=isNotEmpty,exports.isNumber=isNumber$1,exports.isObject=isObject$1,exports.isString=isString$1,exports.normalizeArgs=normalizeArgs$1,exports.validateAsync=validateAsync$1,exports.validateSync=validateSync$1; //# sourceMappingURL=jsonql-params-validator.cjs.js.map diff --git a/packages/validator/dist/jsonql-params-validator.umd.js b/packages/validator/dist/jsonql-params-validator.umd.js index 4658eb8b8f10ea3e7abf04db38e216ad8d830ca2..d71077f02276751d94d0bd55c81ff73f82f3edfd 100644 --- a/packages/validator/dist/jsonql-params-validator.umd.js +++ b/packages/validator/dist/jsonql-params-validator.umd.js @@ -1,2 +1,2 @@ -!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((t=t||self).jsonqlParamsValidator={})}(this,function(t){"use strict";var r="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},n="object"==typeof r&&r&&r.Object===Object&&r,e="object"==typeof self&&self&&self.Object===Object&&self,o=n||e||Function("return this")(),u=o.Symbol,i=Object.prototype,a=i.hasOwnProperty,c=i.toString,f=u?u.toStringTag:void 0;var l=Object.prototype.toString;var s="[object Null]",p="[object Undefined]",v=u?u.toStringTag:void 0;function h(t){return null==t?void 0===t?p:s:v&&v in Object(t)?function(t){var r=a.call(t,f),n=t[f];try{var e=!(t[f]=void 0)}catch(t){}var o=c.call(t);return e&&(r?t[f]=n:delete t[f]),o}(t):function(t){return l.call(t)}(t)}function y(t){return null!=t&&"object"==typeof t}var d="[object Symbol]";function g(t){return"symbol"==typeof t||y(t)&&h(t)==d}function b(t,r){for(var n=-1,e=null==t?0:t.length,o=Array(e);++n>>0,r>>>=0;for(var u=Array(o);++e")){var r=t.replace(Le,"").replace(">","");return r.indexOf("|")?r.split("|"):[r]}return!1}function xe(t,n){var r=t.arg;return 1n.filter(function(t){return!Ee(t)(r)}).length)}).length:n.length>n.filter(function(t){return!Xe(r,t)}).length}function Te(n,e){if(!Xe(e))throw new oo("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===e.length)return[];if(!Xe(n))throw new oo("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case n.length==e.length:return n.map(function(t,r){return{arg:t,index:r,param:e[r]}});case!0===e[0].variable:var o=e[0].type;return n.map(function(t,r){return{arg:t,index:r,param:e[r]||{type:o,name:"_"}}});case n.lengthe.length&&1===e.length:var t,u=["any"];return!1!==(t=ze(e[0].type[0]))&&(u=t),n.map(function(t,r){return{arg:t,index:r,param:e[r]||{type:u,name:"_"}}});default:throw new oo("Could not understand your arguments and parameter structure!",{args:n,params:e})}}function Ne(t,r,n){var e;void 0===n&&(n=!1);var o=Te(t,r),u=o.filter(function(r){return!0===r.param.optional?function(r){var t=r.arg,n=r.param;return!!Ae(t)&&!(n.type.length>n.type.filter(function(t){return uo(t,r)}).length)}(r):!(r.param.type.length>r.param.type.filter(function(t){return uo(t,r)}).length)});return n?((e={})[Ce]=u,e.data=function(t){return t.map(function(t){return t.arg})}(o),e):u}function Fe(t,r){return!!t.filter(function(t){return t===r}).length}var Me=function(t){return""!==Oe(t)&&se(t)},Ce="error",$e="payload",Be="condition",qe="resolverName",De="args",Ie="optional",Je="enumv",Re="checker",Ve="alias",Le="array.<",Qe="type",Ue=Ie,We=Je,Ge="args",Ke=Re,Ye=Ve,He="continue",Xe=function(t,r){return void 0===r&&(r=""),!!_(t)&&(""===r||""===Oe(r)||!(0t.type.filter(function(t){var r;return!!he(n)||(!1!==(r=ze(t))?!xe({arg:n},r):!Ee(t)(n))}).length)}).length}return!1},to=function(n){function e(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];n.apply(this,t),this.message=t[0],this.detail=t[1],this.className=e.name,n.captureStackTrace&&n.captureStackTrace(this,e)}n&&(e.__proto__=n),(e.prototype=Object.create(n&&n.prototype)).constructor=e;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,t),e}(Error),ro=function(n){function e(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];n.apply(this,t),this.message=t[0],this.detail=t[1],this.className=e.name,n.captureStackTrace&&n.captureStackTrace(this,e)}n&&(e.__proto__=n),(e.prototype=Object.create(n&&n.prototype)).constructor=e;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,t),e}(Error),no=function(n){function e(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];n.apply(this,t),this.message=t[0],this.detail=t[1],this.className=e.name,n.captureStackTrace&&n.captureStackTrace(this,e)}n&&(e.__proto__=n),(e.prototype=Object.create(n&&n.prototype)).constructor=e;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,t),e}(Error),eo=function(n){function e(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];n.apply(this,t),this.message=t[0],this.detail=t[1],this.className=e.name,n.captureStackTrace&&n.captureStackTrace(this,e)}n&&(e.__proto__=n),(e.prototype=Object.create(n&&n.prototype)).constructor=e;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,t),e}(Error),oo=function(n){function e(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];n.apply(this,t),this.message=t[0],this.detail=t[1],this.className=e.name,n.captureStackTrace&&n.captureStackTrace(this,e)}n&&(e.__proto__=n),(e.prototype=Object.create(n&&n.prototype)).constructor=e;var t={name:{configurable:!0},statusCode:{configurable:!0}};return t.name.get=function(){return"JsonqlError"},t.statusCode.get=function(){return-1},Object.defineProperties(e,t),e}(Error),uo=function(t,r){var n;switch(!0){case"object"===t:return!function(t){var r=t.arg,n=t.param,e=[r];return Array.isArray(n.keys)&&n.keys.length&&e.push(n.keys),Ze.apply(null,e)}(r);case"array"===t:return!Xe(r.arg);case!1!==(n=ze(t)):return!xe(r,n);default:return!Ee(t)(r.arg)}},io=function(t,r){var n=Object.keys(t);return Fe(n,r)},ao=function(t){return!Ae(t)};function co(t,r){var n=me(r,function(t,r){return!t[Ye]});return function(t,r){return Vn(t,r)}(n,{})?t:function(t,e){var o={};return e=re(e),oe(t,function(t,r,n){ut(o,e(t,r,n),t)}),o}(t,function(t,r){return function(t,r){return function(t,e,r){var o;return r(t,function(t,r,n){if(e(t,r,n))return o=r,!1}),o}(t,re(r),oe)}(n,function(t){return t.alias===r})||r})}function fo(t,r){var n=function(t,r){var n=co(t,r);return{pristineValues:ye(me(r,function(t,r){return io(n,r)}),function(t){return t.args}),checkAgainstAppProps:me(r,function(t,r){return!io(n,r)}),config:n}}(t,r),e=n.config,o=n.pristineValues;return[function(o,t){return ye(t,function(t,r){var n,e;return he(o[r])||!0===t[Ue]&&ao(o[r])?ge({},t,((n={})[He]=!0,n)):((e={})[Ge]=o[r],e[Qe]=t[Qe],e[Ue]=t[Ue]||!1,e[We]=t[We]||!1,e[Ke]=t[Ke]||!1,e)})}(e,n.checkAgainstAppProps),o]}var lo=function(t){return Xe(t)?t:[t]};var so=function(t,r){return!Xe(r)||function(t,r){return!!t.filter(function(t){return t===r}).length}(r,t)},po=function(t,r){try{return!!x(r)&&r.apply(null,[t])}catch(t){return!1}};function vo(e){return function(t,r){if(t[He])return t[Ge];var n=function(t,r){var n,e=[[t[Ge]],[(n={},n[Qe]=lo(t[Qe]),n[Ue]=t[Ue],n)]];return Reflect.apply(r,null,e)}(t,e);if(n.length)throw new ro(r,n);if(!1!==t[We]&&!so(t[Ge],t[We]))throw new to(r);if(!1!==t[Ke]&&!po(t[Ge],t[Ke]))throw new no(r);return t[Ge]}}function ho(t,r){var n=t[0],e=t[1],o=ye(n,vo(r));return ge(o,e)}function yo(t,r,n,e){return void 0===t&&(t={}),function(t,r){return Promise.resolve(fo(t,r))}(t,r).then(function(t){return ho(t,e)}).then(function(t){return ge({},t,n)})}function go(t,r,n,e,o,u){void 0===n&&(n=!1),void 0===e&&(e=!1),void 0===o&&(o=!1),void 0===u&&(u=!1);var i={};return i.args=t,i.type=r,!0===n&&(i[Ie]=!0),Xe(e)&&(i[Je]=e),x(o)&&(i[Re]=o),se(u)&&(i[Ve]=u),i}function bo(t){return Me(t)?JSON.parse(t):t}function _o(t){return Object.keys(t)[0]}function jo(t,r,n){var e;if(void 0===r&&(r=[]),void 0===n&&(n=!1),Me(t)&&Xe(r)){var o={};return o[De]=r,!0===n?o:((e={})[t]=o,e)}throw new eo("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:r})}function mo(t,r,n,e){var o;void 0===n&&(n={}),void 0===e&&(e=!1);var u={};if(u[$e]=r,u[Be]=n,!0===e)return u;if(Me(t))return(o={})[t]=u,o;throw new eo("[createMutation] expect resolverName to be string!",{resolverName:t,payload:r,condition:n})}function wo(t,r){var n;if(t&&Ze(r)){var e=r[t];if(e[De])return(n={})[qe]=t,n[De]=e[De],n}return!1}function Oo(t,r){var n;if(t&&Ze(r)){var e=r[t];if(e)return(n={})[qe]=t,n[$e]=e[$e],n[Be]=e[Be],n}return!1}function Ao(e,o,u){return void 0===u&&(u=!1),new Promise(function(t,r){var n=Ne(e,o,u);return u?n[Ce].length?r(n[Ce]):t(n.data):n.length?r(n):t([])})}function So(t,r,n){void 0===n&&(n={});var e=n[Ie],o=n[Je],u=n[Re],i=n[Ve];return go.apply(null,[t,r,e,o,u,i])}function Po(t){return Ze(t)&&(io(t,"query")||io(t,"mutation")||io(t,"socket"))}function ko(t,r,n){return void 0===r&&(r=[]),void 0===n&&(n=!1),JSON.stringify(jo(t,r,n))}function Eo(t,r,n,e){return void 0===n&&(n={}),void 0===e&&(e=!1),JSON.stringify(mo(t,r,n,e))}function zo(t){var r=bo(t),n=wo(_o(r),r);if(!1!==n)return n;throw new eo("[getQueryArgs] Payload is malformed!",t)}function xo(t){var r=bo(t),n=Oo(_o(r),r);if(!1!==n)return n;throw new eo("[getMutationArgs] Payload is malformed!",t)}var To,No,Fo=Ze,Mo=ke,Co=Me,$o=Pe,Bo=Se,qo=Xe,Do=Ae,Io=Te,Jo=Ne,Ro=go,Vo=(To=Ne,function(t,r,n){return void 0===n&&(n={}),yo(t,r,n,To)}),Lo=(No=Ne,function(t,r,n){return void 0===n&&(n={}),function(t,r,n,e){return void 0===t&&(t={}),ge(ho(fo(t,r),e),n)}(t,r,n,No)}),Qo=Fe,Uo=io,Wo=jo,Go=mo,Ko=wo,Yo=Oo,Ho=_o;t.JSONQL_PARAMS_VALIDATOR_INFO="version: 1.4.3 module: umd",t.checkConfig=Lo,t.checkConfigAsync=Vo,t.constructConfig=Ro,t.createConfig=So,t.createMutation=Go,t.createMutationStr=Eo,t.createQuery=Wo,t.createQueryStr=ko,t.getMutationFromArgs=Yo,t.getMutationFromPayload=xo,t.getNameFromPayload=Ho,t.getQueryFromArgs=Ko,t.getQueryFromPayload=zo,t.inArray=Qo,t.isAny=Mo,t.isArray=qo,t.isBoolean=$o,t.isContract=Po,t.isKeyInObject=Uo,t.isNotEmpty=Do,t.isNumber=Bo,t.isObject=Fo,t.isString=Co,t.normalizeArgs=Io,t.validateAsync=Ao,t.validateSync=Jo,Object.defineProperty(t,"__esModule",{value:!0})}); +!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((t=t||self).jsonqlParamsValidator={})}(this,function(t){"use strict";var r="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},n="object"==typeof r&&r&&r.Object===Object&&r,e="object"==typeof self&&self&&self.Object===Object&&self,o=n||e||Function("return this")(),u=o.Symbol,i=Object.prototype,a=i.hasOwnProperty,c=i.toString,f=u?u.toStringTag:void 0;var l=Object.prototype.toString;var s="[object Null]",p="[object Undefined]",v=u?u.toStringTag:void 0;function h(t){return null==t?void 0===t?p:s:v&&v in Object(t)?function(t){var r=a.call(t,f),n=t[f];try{var e=!(t[f]=void 0)}catch(t){}var o=c.call(t);return e&&(r?t[f]=n:delete t[f]),o}(t):function(t){return l.call(t)}(t)}function y(t){return null!=t&&"object"==typeof t}var d="[object Symbol]";function g(t){return"symbol"==typeof t||y(t)&&h(t)==d}function b(t,r){for(var n=-1,e=null==t?0:t.length,o=Array(e);++n>>0,r>>>=0;for(var u=Array(o);++e")){var r=t.replace(Ie,"").replace(">","");return r.indexOf("|")?r.split("|"):[r]}return!1}function xe(t,n){var r=t.arg;return 1n.filter(function(t){return!Ee(t)(r)}).length)}).length:n.length>n.filter(function(t){return!Ye(r,t)}).length}function Te(){try{if(window||document)return!0}catch(t){}return!1}var Ne=function(t){return""!==Oe(t)&&se(t)},Fe="error",Me="payload",Ce="condition",$e="resolverName",Be="args",Re="optional",Ve="enumv",qe="checker",De="alias",Ie="array.<",Je="type",Le=Re,Qe=Ve,Ue="args",We=qe,Ge=De,Ke="continue",Ye=function(t,r){return void 0===r&&(r=""),!!_(t)&&(""===r||""===Oe(r)||!(0t.type.filter(function(t){var r;return!!he(n)||(!1!==(r=ze(t))?!xe({arg:n},r):!Ee(t)(n))}).length)}).length}return!1};function Xe(){return Te()?"browser":function(){try{if(!Te()&&r)return!0}catch(t){}return!1}()?"node":"unknown"}var Ze=function(n){function t(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];n.apply(this,t)}return n&&(t.__proto__=n),((t.prototype=Object.create(n&&n.prototype)).constructor=t).where=function(){return Xe()},t}(Error),to=function(n){function e(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];n.apply(this,t),this.message=t[0],this.detail=t[1],this.className=e.name,n.captureStackTrace&&n.captureStackTrace(this,e)}n&&(e.__proto__=n),(e.prototype=Object.create(n&&n.prototype)).constructor=e;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(e,t),e}(Error),ro=function(n){function e(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];n.apply(this,t),this.message=t[0],this.detail=t[1],this.className=e.name,n.captureStackTrace&&n.captureStackTrace(this,e)}n&&(e.__proto__=n),(e.prototype=Object.create(n&&n.prototype)).constructor=e;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(e,t),e}(Error),no=function(n){function e(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];n.apply(this,t),this.message=t[0],this.detail=t[1],this.className=e.name,n.captureStackTrace&&n.captureStackTrace(this,e)}n&&(e.__proto__=n),(e.prototype=Object.create(n&&n.prototype)).constructor=e;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(e,t),e}(Error),eo=function(n){function e(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];n.apply(this,t),this.message=t[0],this.detail=t[1],this.className=e.name,Error.captureStackTrace&&Error.captureStackTrace(this,e)}n&&(e.__proto__=n),(e.prototype=Object.create(n&&n.prototype)).constructor=e;var t={name:{configurable:!0}};return t.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(e,t),e}(Ze),oo=function(n){function e(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];n.apply(this,t),this.message=t[0],this.detail=t[1],this.className=e.name,Error.captureStackTrace&&Error.captureStackTrace(this,e)}n&&(e.__proto__=n),(e.prototype=Object.create(n&&n.prototype)).constructor=e;var t={name:{configurable:!0},statusCode:{configurable:!0}};return t.name.get=function(){return"JsonqlError"},t.statusCode.get=function(){return-1},Object.defineProperties(e,t),e}(Ze);function uo(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];try{window&&window.debug&&Reflect.apply(console.log,console,t)}catch(t){}}function io(t,r){return he(t)?!0!==r.optional||he(r.defaultvalue)?null:r.defaultvalue:t}function ao(n,o){if(!Ye(o))throw new oo("params is not an array! Did something gone wrong when you generate the contract.json?");if(0===o.length)return[];if(!Ye(n))throw new oo("args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)");switch(!0){case n.length==o.length:return uo(1),n.map(function(t,r){return{arg:t,index:r,param:o[r]}});case!0===o[0].variable:uo(2);var e=o[0].type;return n.map(function(t,r){return{arg:t,index:r,param:o[r]||{type:e,name:"_"}}});case n.lengtho.length:uo(4);var u=o.length,i=["any"];return n.map(function(t,r){var n=u<=r||!!o[r].optional,e=o[r]||{type:i,name:"_"+r};return{arg:n?io(t,e):t,index:r,param:e,optional:n}});default:throw uo(5),new oo("Could not understand your arguments and parameter structure!",{args:n,params:o})}}function co(t,r,n){var e;void 0===n&&(n=!1);var o=ao(t,r),u=o.filter(function(r){return!0===r.optional||!0===r.param.optional?function(r){var t=r.arg,n=r.param;return!!Ae(t)&&!(n.type.length>n.type.filter(function(t){return lo(t,r)}).length)}(r):!(r.param.type.length>r.param.type.filter(function(t){return lo(t,r)}).length)});return n?((e={})[Fe]=u,e.data=function(t){return t.map(function(t){return t.arg})}(o),e):u}function fo(t,r){return!!t.filter(function(t){return t===r}).length}var lo=function(t,r){var n;switch(!0){case"object"===t:return!function(t){var r=t.arg,n=t.param,e=[r];return Array.isArray(n.keys)&&n.keys.length&&e.push(n.keys),He.apply(null,e)}(r);case"array"===t:return!Ye(r.arg);case!1!==(n=ze(t)):return!xe(r,n);default:return!Ee(t)(r.arg)}},so=function(t,r){var n=Object.keys(t);return fo(n,r)},po=function(t){return!Ae(t)};function vo(t,r){var n=me(r,function(t,r){return!t[Ge]});return function(t,r){return Jn(t,r)}(n,{})?t:function(t,e){var o={};return e=re(e),oe(t,function(t,r,n){ut(o,e(t,r,n),t)}),o}(t,function(t,r){return function(t,r){return function(t,e,r){var o;return r(t,function(t,r,n){if(e(t,r,n))return o=r,!1}),o}(t,re(r),oe)}(n,function(t){return t.alias===r})||r})}function ho(t,r){var n=function(t,r){var n=vo(t,r);return{pristineValues:ye(me(r,function(t,r){return so(n,r)}),function(t){return t.args}),checkAgainstAppProps:me(r,function(t,r){return!so(n,r)}),config:n}}(t,r),e=n.config,o=n.pristineValues;return[function(o,t){return ye(t,function(t,r){var n,e;return he(o[r])||!0===t[Le]&&po(o[r])?ge({},t,((n={})[Ke]=!0,n)):((e={})[Ue]=o[r],e[Je]=t[Je],e[Le]=t[Le]||!1,e[Qe]=t[Qe]||!1,e[We]=t[We]||!1,e)})}(e,n.checkAgainstAppProps),o]}var yo=function(t){return Ye(t)?t:[t]};var go=function(t,r){return!Ye(r)||function(t,r){return!!t.filter(function(t){return t===r}).length}(r,t)},bo=function(t,r){try{return!!x(r)&&r.apply(null,[t])}catch(t){return!1}};function _o(e){return function(t,r){if(t[Ke])return t[Ue];var n=function(t,r){var n,e=[[t[Ue]],[(n={},n[Je]=yo(t[Je]),n[Le]=t[Le],n)]];return Reflect.apply(r,null,e)}(t,e);if(n.length)throw uo("runValidationAction",r,t),new ro(r,n);if(!1!==t[Qe]&&!go(t[Ue],t[Qe]))throw uo(Qe,t[Qe]),new to(r);if(!1!==t[We]&&!bo(t[Ue],t[We]))throw uo(We,t[We]),new no(r);return t[Ue]}}function jo(t,r){var n=t[0],e=t[1],o=ye(n,_o(r));return ge(o,e)}function mo(t,r,n,e){return void 0===t&&(t={}),function(t,r){return Promise.resolve(ho(t,r))}(t,r).then(function(t){return jo(t,e)}).then(function(t){return ge({},t,n)})}function wo(t,r,n,e,o,u){void 0===n&&(n=!1),void 0===e&&(e=!1),void 0===o&&(o=!1),void 0===u&&(u=!1);var i={};return i.args=t,i.type=r,!0===n&&(i[Re]=!0),Ye(e)&&(i[Ve]=e),x(o)&&(i[qe]=o),se(u)&&(i[De]=u),i}function Oo(t){return Ne(t)?JSON.parse(t):t}function Ao(t){return Object.keys(t)[0]}function So(t,r,n){var e;if(void 0===r&&(r=[]),void 0===n&&(n=!1),Ne(t)&&Ye(r)){var o={};return o[Be]=r,!0===n?o:((e={})[t]=o,e)}throw new eo("[createQuery] expect resolverName to be string and args to be array!",{resolverName:t,args:r})}function Po(t,r,n,e){var o;void 0===n&&(n={}),void 0===e&&(e=!1);var u={};if(u[Me]=r,u[Ce]=n,!0===e)return u;if(Ne(t))return(o={})[t]=u,o;throw new eo("[createMutation] expect resolverName to be string!",{resolverName:t,payload:r,condition:n})}function ko(t,r){var n;if(t&&He(r)){var e=r[t];if(e[Be])return(n={})[$e]=t,n[Be]=e[Be],n}return!1}function Eo(t,r){var n;if(t&&He(r)){var e=r[t];if(e)return(n={})[$e]=t,n[Me]=e[Me],n[Ce]=e[Ce],n}return!1}function zo(e,o,u){return void 0===u&&(u=!1),new Promise(function(t,r){var n=co(e,o,u);return u?n[Fe].length?r(n[Fe]):t(n.data):n.length?r(n):t([])})}function xo(t,r,n){void 0===n&&(n={});var e=n[Re],o=n[Ve],u=n[qe],i=n[De];return wo.apply(null,[t,r,e,o,u,i])}function To(t){return He(t)&&(so(t,"query")||so(t,"mutation")||so(t,"socket"))}function No(t,r,n){return void 0===r&&(r=[]),void 0===n&&(n=!1),JSON.stringify(So(t,r,n))}function Fo(t,r,n,e){return void 0===n&&(n={}),void 0===e&&(e=!1),JSON.stringify(Po(t,r,n,e))}function Mo(t){var r=Oo(t),n=ko(Ao(r),r);if(!1!==n)return n;throw new eo("[getQueryArgs] Payload is malformed!",t)}function Co(t){var r=Oo(t),n=Eo(Ao(r),r);if(!1!==n)return n;throw new eo("[getMutationArgs] Payload is malformed!",t)}var $o,Bo,Ro=He,Vo=ke,qo=Ne,Do=Pe,Io=Se,Jo=Ye,Lo=Ae,Qo=ao,Uo=co,Wo=wo,Go=($o=co,function(t,r,n){return void 0===n&&(n={}),mo(t,r,n,$o)}),Ko=(Bo=co,function(t,r,n){return void 0===n&&(n={}),function(t,r,n,e){return void 0===t&&(t={}),ge(jo(ho(t,r),e),n)}(t,r,n,Bo)}),Yo=fo,Ho=so,Xo=So,Zo=Po,tu=ko,ru=Eo,nu=Ao;t.JSONQL_PARAMS_VALIDATOR_INFO="version: 1.4.4 module: umd",t.checkConfig=Ko,t.checkConfigAsync=Go,t.constructConfig=Wo,t.createConfig=xo,t.createMutation=Zo,t.createMutationStr=Fo,t.createQuery=Xo,t.createQueryStr=No,t.getMutationFromArgs=ru,t.getMutationFromPayload=Co,t.getNameFromPayload=nu,t.getQueryFromArgs=tu,t.getQueryFromPayload=Mo,t.inArray=Yo,t.isAny=Vo,t.isArray=Jo,t.isBoolean=Do,t.isContract=To,t.isKeyInObject=Ho,t.isNotEmpty=Lo,t.isNumber=Io,t.isObject=Ro,t.isString=qo,t.normalizeArgs=Qo,t.validateAsync=zo,t.validateSync=Uo,Object.defineProperty(t,"__esModule",{value:!0})}); //# sourceMappingURL=jsonql-params-validator.umd.js.map diff --git a/packages/validator/package.json b/packages/validator/package.json index bc456fb468d7925c5badac0a0f4417eeca2af8fe..6d58239d6cf3d73c785dc15332936b3a861732b9 100644 --- a/packages/validator/package.json +++ b/packages/validator/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-params-validator", - "version": "1.4.3", + "version": "1.4.4", "description": "JSONQL parameters validator written in ES6+ to use with the client / server", "module": "index.js", "browser": "dist/jsonql-params-validator.umd.js", @@ -14,6 +14,7 @@ "scripts": { "prepare": "npm run build", "test": "DEBUG=jsonql-params-validator* ava", + "test:mut": "npm run build && DEBUG=jsonql-params-validator* ava ./tests/mutation.test.js", "test:result": "DEBUG=jsonql-params-validator* ava ./tests/validate-result.test.js", "test:config:check": "DEBUG=jsonql-params-validator* ava ./tests/config-values.test.js", "test:basic": "DEBUG=jsonql-params-validator* ava ./tests/primitive-type.test.js", @@ -38,22 +39,22 @@ "jsonql" ], "dependencies": { - "jsonql-constants": "^1.7.6", - "jsonql-errors": "^1.0.9", - "lodash-es": "^4.17.11" + "jsonql-constants": "^1.7.9", + "jsonql-errors": "^1.1.2", + "lodash-es": "^4.17.15" }, "devDependencies": { - "ava": "^2.1.0", + "ava": "^2.3.0", "debug": "^4.1.1", "esm": "^3.2.25", "fs-extra": "^8.1.0", - "rollup": "^1.16.3", + "rollup": "^1.19.4", "rollup-plugin-alias": "^1.5.2", "rollup-plugin-async": "^1.2.0", - "rollup-plugin-buble": "^0.19.6", + "rollup-plugin-buble": "^0.19.8", "rollup-plugin-bundle-size": "^1.0.3", - "rollup-plugin-commonjs": "^10.0.1", - "rollup-plugin-copy": "^3.0.0", + "rollup-plugin-commonjs": "^10.0.2", + "rollup-plugin-copy": "^3.1.0", "rollup-plugin-json": "^4.0.0", "rollup-plugin-node-builtins": "^2.1.2", "rollup-plugin-node-globals": "^1.4.0", @@ -61,7 +62,7 @@ "rollup-plugin-replace": "^2.2.0", "rollup-plugin-serve": "^1.0.1", "rollup-plugin-uglify": "^6.0.2", - "server-io-core": "^1.1.0", + "server-io-core": "^1.2.0", "superkoa": "^1.0.3" }, "repository": { diff --git a/packages/validator/src/log.js b/packages/validator/src/log.js new file mode 100644 index 0000000000000000000000000000000000000000..4fc773ca9f17303f751fc3900bff15e0ce3924d7 --- /dev/null +++ b/packages/validator/src/log.js @@ -0,0 +1,12 @@ +/** + * just a simple util for helping to debug + * @param {array} args arguments + * @return {void} + */ +export default function log(...args) { + try { + if (window && window.debug) { + Reflect.apply(console.log, console, args) + } + } catch(e) {} +} diff --git a/packages/validator/src/options/run-validation.js b/packages/validator/src/options/run-validation.js index 317c33ab2c35ee876879bb1f3610c081b3348b35..31e9614203a0ceea31023f58e6123df77ca62545 100644 --- a/packages/validator/src/options/run-validation.js +++ b/packages/validator/src/options/run-validation.js @@ -1,7 +1,7 @@ // breaking the whole thing up to see what cause the multiple calls issue import { isFunction, merge, mapValues } from 'lodash-es' - +import log from '../log' import { TYPE_KEY, OPTIONAL_KEY, @@ -99,13 +99,15 @@ function runValidationAction(cb) { } const check = validateHandler(value, cb) if (check.length) { - // debugFn('runValidationAction', key, value) + log('runValidationAction', key, value) throw new JsonqlTypeError(key, check) } if (value[ENUM_KEY] !== false && !enumHandler(value[ARGS_KEY], value[ENUM_KEY])) { + log(ENUM_KEY, value[ENUM_KEY]) throw new JsonqlEnumError(key) } if (value[CHECKER_KEY] !== false && !checkerHandler(value[ARGS_KEY], value[CHECKER_KEY])) { + log(CHECKER_KEY, value[CHECKER_KEY]) throw new JsonqlCheckerError(key) } return value[ARGS_KEY] diff --git a/packages/validator/src/validator.js b/packages/validator/src/validator.js index 29c820b53f21afd6ca8bd28872ad4673a88859f5..4b98f0facf1631b71fc03fe44393bd4573652bfb 100644 --- a/packages/validator/src/validator.js +++ b/packages/validator/src/validator.js @@ -20,7 +20,7 @@ import { } from './constants' import { DATA_KEY, ERROR_KEY } from 'jsonql-constants' import { JsonqlError } from 'jsonql-errors' - +import log from './log' // import debug from 'debug' // const debugFn = debug('jsonql-params-validator:validator') // also export this for use in other places @@ -105,14 +105,16 @@ export const normalizeArgs = function(args, params) { // fall through switch switch(true) { case args.length == params.length: // standard + log(1) return args.map((arg, i) => ( { arg, index: i, param: params[i] } - )); + )) case params[0].variable === true: // using spread syntax + log(2) const type = params[0].type; return args.map((arg, i) => ( { @@ -120,9 +122,10 @@ export const normalizeArgs = function(args, params) { index: i, // keep the index for reference param: params[i] || { type, name: '_' } } - )); + )) // with optional defaultValue parameters case args.length < params.length: + log(3) return params.map((param, i) => ( { param, @@ -130,25 +133,34 @@ export const normalizeArgs = function(args, params) { arg: getOptionalValue(args[i], param), optional: param.optional || false } - )); + )) // this one pass more than it should have anything after the args.length will be cast as any type - case args.length > params.length && params.length === 1: + case args.length > params.length: + log(4) + let ctn = params.length; // this happens when we have those array. type - let tmp, _type = [ DEFAULT_TYPE ]; - // we only looking at the first one, this might be a @BUG! + let _type = [ DEFAULT_TYPE ] + // we only looking at the first one, this might be a @BUG + /* if ((tmp = isArrayLike(params[0].type[0])) !== false) { _type = tmp; - } - // if not then we fall back to the following - return args.map((arg, i) => ( - { - arg, + } */ + // if we use the params as guide then the rest will get throw out + // which is not what we want, instead, anything without the param + // will get a any type and optional flag + return args.map((arg, i) => { + let optional = i >= ctn ? true : !!params[i].optional + let param = params[i] || { type: _type, name: `_${i}` } + return { + arg: optional ? getOptionalValue(arg, param) : arg, index: i, - param: params[i] || { type: _type, name: '_' } + param, + optional } - )); + }) // @TODO find out if there is more cases not cover default: // this should never happen + log(5) // debugFn('args', args) // debugFn('params', params) // this is unknown therefore we just throw it! @@ -175,7 +187,8 @@ const processReturn = result => result.map(r => r.arg) export const validateSync = function(args, params, withResult = false) { let cleanArgs = normalizeArgs(args, params) let checkResult = cleanArgs.filter(p => { - if (p.param.optional === true) { + // v1.4.4 this fixed the problem, the root level optional is from the last fn + if (p.optional === true || p.param.optional === true) { return optionalHandler(p) } // because array of types means OR so if one pass means pass diff --git a/packages/validator/tests/check-node-client-async.test.js b/packages/validator/tests/check-node-client-async.test.js index a037a957a046eedb749c6deecdb77042535108f5..2f190660c000a49cb89361adc23edb08966847b0 100644 --- a/packages/validator/tests/check-node-client-async.test.js +++ b/packages/validator/tests/check-node-client-async.test.js @@ -8,7 +8,7 @@ const { const debug = require('debug')('jsonql-params-validator:check-node-client-async') const nodeClientCheckConfig = require('./fixtures/node-client-config') const { join, resolve } = require('path') -const contractDir = resolve(join(__dirname, 'fixtures', 'tmp')) +const contractDir = resolve(join(__dirname, 'fixtures')) const hostname = 'https://some-where-else.com'; const contractKey = '12345678' // @NOTE strange behavior this one can use cb but not the other other two??? diff --git a/packages/validator/tests/combine.test.js b/packages/validator/tests/combine.test.js index c8da1e24a1ccd9684e72e7582adcc86f64b6b660..4a748a8eb767b35fda480325413dea385b10b7e0 100644 --- a/packages/validator/tests/combine.test.js +++ b/packages/validator/tests/combine.test.js @@ -76,15 +76,15 @@ test('Test an array with array. pattern (query.arrayOfParams)', t => { t.deepEqual([], validateSync(argsPass, params)) let argsFail = [ [3,2,'abc'] - ]; + ] const result = validateSync(argsFail, params) // debug('test array result', result); // the reason it's 0 because this is the index of params in the array // not within which value failed t.is(0, result[0].index) -}); +}) -// @TODO need to fix this then release as version one +// This failed again? test('Test an array with array. pattern', t => { let args = [1, 2, 3, 'a', 'b'] const params = [{ @@ -96,7 +96,9 @@ test('Test an array with array. pattern', t => { // this one is problematic const failArgs = args.concat([{msg: 'should not be here'}]) const result = validateSync([failArgs], params) + debug('test failed array. result', result) + t.notDeepEqual([], result) }) diff --git a/packages/validator/tests/fixtures/public-contract.json b/packages/validator/tests/fixtures/public-contract.json new file mode 100644 index 0000000000000000000000000000000000000000..6a7713b9f89e1f944d7a88732bb6a38343864bf7 --- /dev/null +++ b/packages/validator/tests/fixtures/public-contract.json @@ -0,0 +1,127 @@ +{ + "query": { + "helloWorld": { + "params": [], + "returns": [ + { + "type": "string", + "description": "stock message" + } + ] + }, + "causeError": { + "params": [ + { + "type": [ + "any" + ], + "name": "x", + "description": "param" + } + ], + "returns": [ + { + "type": [ + "any" + ], + "description": "unknown" + } + ] + }, + "getUser": { + "params": [ + { + "type": [ + "string" + ], + "name": "args", + "variable": true, + "description": "passing unknown number of param" + } + ], + "returns": [ + { + "type": [ + "any" + ], + "description": "extract from last of the args" + } + ] + }, + "testList": { + "params": [ + { + "type": [ + "number" + ], + "name": "num", + "description": "a number" + } + ], + "returns": [ + { + "type": [ + "object" + ], + "description": "@TODO need to figure out how to give keys to the returns" + } + ] + } + }, + "mutation": { + "updateList": { + "params": [ + { + "type": [ + "object" + ], + "name": "payload", + "keys": [ + { + "type": [ + "number" + ], + "name": "user", + "parent": "payload" + } + ] + }, + { + "type": [ + "object" + ], + "name": "condition" + } + ], + "returns": [ + { + "type": [ + "object" + ], + "description": "with user as key" + } + ] + }, + "updateMsService": { + "params": [ + { + "type": [ + "string" + ], + "name": "payload", + "description": "incoming" + } + ], + "returns": [ + { + "type": [ + "string" + ], + "description": "msg return from nodeClient" + } + ] + } + }, + "auth": {}, + "timestamp": 1566134875010 +} diff --git a/packages/validator/tests/fixtures/ws-check-options.js b/packages/validator/tests/fixtures/ws-check-options.js index 795a4ecb1f283315b67fbf018feef48440a6ffc6..2cb1c177fb267d8208179ea85f80b7ed98586dc3 100644 --- a/packages/validator/tests/fixtures/ws-check-options.js +++ b/packages/validator/tests/fixtures/ws-check-options.js @@ -27,7 +27,7 @@ const constProps = { const defaultOptions = { // we will use this for determine the socket.io client type as well - useJwt: createConfig(false, [BOOLEAN_TYPE, STRING_TYPE]), + useJwt: createConfig(true, [BOOLEAN_TYPE, STRING_TYPE]), hostname: createConfig(false, [STRING_TYPE]), namespace: createConfig(JSONQL_PATH, [STRING_TYPE]), wsOptions: createConfig({transports: ['websocket']}, [OBJECT_TYPE]), diff --git a/packages/validator/tests/fixtures/ws-server-check-options.js b/packages/validator/tests/fixtures/ws-server-check-options.js index 31866b20ed9fc99fc14ebea6434b2240c06ef8da..f650f9ef87119a455a52679c92265c192b9a86b3 100644 --- a/packages/validator/tests/fixtures/ws-server-check-options.js +++ b/packages/validator/tests/fixtures/ws-server-check-options.js @@ -48,7 +48,7 @@ const defaultOptions = { contract: createConfig({}, [OBJECT_TYPE]), enableAuth: createConfig(false, [BOOLEAN_TYPE]), // this option now is only for passing the key - useJwt: createConfig('', [STRING_TYPE, BOOLEAN_TYPE]), // need to double check this + useJwt: createConfig(true, [STRING_TYPE, BOOLEAN_TYPE]), // need to double check this // we don't actually use this two contractDir: createConfig('', [STRING_TYPE]), resolverDir: createConfig('', [STRING_TYPE]), diff --git a/packages/validator/tests/mutation.test.js b/packages/validator/tests/mutation.test.js new file mode 100644 index 0000000000000000000000000000000000000000..6429064f53ebc8e77ef1d21c048aa623aaea6abd --- /dev/null +++ b/packages/validator/tests/mutation.test.js @@ -0,0 +1,15 @@ +// find the edge case when a mutation only required a payload but no condition +// then the args = [payload, undefined] but the validation failed +const test = require('ava') +const { join } = require('path') +const { validateSync } = require('../dist/jsonql-params-validator.cjs') +const fsx = require('fs-extra') +const contract = fsx.readJsonSync(join(__dirname, 'fixtures', 'public-contract.json')) +const debug = require('debug')('jsonql-params-validator:test:mutation') + +test(`It should able to handle the mutation validation when only payload has been defined`, t => { + const param = contract.mutation.updateMsService.params; + const result = validateSync(['test', undefined], param) + debug('%O', result) + t.false(!!result.length) +}) diff --git a/packages/validator/tests/ws-check-options.test.js b/packages/validator/tests/ws-check-options.test.js index 6eda05cf9f89aa63460f02acefa24d24477a32a3..e2a1e5f9d034e3177f1beeab9ce15745de85f71a 100644 --- a/packages/validator/tests/ws-check-options.test.js +++ b/packages/validator/tests/ws-check-options.test.js @@ -5,35 +5,31 @@ const fsx = require('fs-extra') const baseDir = join(__dirname, 'fixtures') const contract = fsx.readJsonSync(join(baseDir, 'contract.json')) - -const contractDir = baseDir; const resolverDir = join(baseDir, 'html') const wsServerConfig = require('./fixtures/ws-server-check-options') const debug = require('debug')('jsonql-params-validator:test:ws-check-options') -// const wsClientConfig = require('./fixtures/ws-check-option') -test.cb('it should able to pass the useJwt option', t => { +test.cb('This test is for testing the ws server configuration setup', t => { t.plan(1) let config = { - contractDir, + contractDir: baseDir, resolverDir, contract, serverType: 'ws', enableAuth: true, - // useJwt: true, keysDir: join(__dirname, 'fixtures', 'keys') } wsServerConfig(config) .then(opts => { - debug(opts) + debug('opts', opts) t.pass() t.end() }) .catch( err => { - debug(err) + debug('err', err) t.fail() t.end() })