diff --git a/packages/common/.gitignore b/packages/common/.gitignore index 57bf2e6855..3cc4dfd11a 100644 --- a/packages/common/.gitignore +++ b/packages/common/.gitignore @@ -40,4 +40,4 @@ flow-typed/npm/* .idea npm-debug.log.* -dist +lib diff --git a/packages/common/lib/common/apiWrapper.js.map b/packages/common/lib/common/apiWrapper.js.map index a1ed6bc2e7..0be7aeeb0e 100644 --- a/packages/common/lib/common/apiWrapper.js.map +++ b/packages/common/lib/common/apiWrapper.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/common/apiWrapper.js"],"names":["apiWrapper","app","eventNamespace","isAuthorized","eventContext","func","pushCallStack","handleNotAuthorized","startDate","Date","now","elapsed","publish","onBegin","params","result","publishComplete","publishError","apiWrapperSync","error","err","UnauthorisedError","seedCallId","callId","createCallStack","threadCallId","stack","calls","push","namespace","popCallStack","pop","length","ctx","onError","endcontext","onComplete"],"mappings":"+ZAAA;AACA;AACA;;AAEO,IAAMA,UAAU,sHAAG;AACxBC,EAAAA,GADwB;AAExBC,EAAAA,cAFwB;AAGxBC,EAAAA,YAHwB;AAIxBC,EAAAA,YAJwB;AAKxBC,EAAAA,IALwB;;;AAQxBC,YAAAA,aAAa,CAACL,GAAD,EAAMC,cAAN,CAAb,CARwB;;AAUnBC,YAAAA,YAAY,CAACF,GAAD,CAVO;AAWtBM,YAAAA,mBAAmB,CAACN,GAAD,EAAMG,YAAN,EAAoBF,cAApB,CAAnB,CAXsB;;;;AAelBM,YAAAA,SAfkB,GAeNC,IAAI,CAACC,GAAL,EAfM;AAgBlBC,YAAAA,OAhBkB,GAgBR,SAAVA,OAAU,WAAMF,IAAI,CAACC,GAAL,KAAaF,SAAnB,EAhBQ;;;AAmBhBP,cAAAA,GAAG,CAACW,OAAJ,CAAYV,cAAc,CAACW,OAA3B,EAAoCT,YAApC,CAnBgB,mCAMrBU,MANqB,uEAMrBA,MANqB;;AAqBDT,cAAAA,IAAI,MAAJ,SAAQS,MAAR,CArBC,UAqBhBC,MArBgB;;AA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,OAJmB;AAKnBS,EAAAA,GALmB;;AAOba,YAAAA,GAPa,GAOP,mBAAU7B,YAAV,CAPO;AAQnB6B,YAAAA,GAAG,CAACd,KAAJ,GAAYC,GAAZ;AACAa,YAAAA,GAAG,CAACtB,OAAJ,GAAcA,OAAO,EAArB,CATmB;AAUbV,cAAAA,GAAG,CAACW,OAAJ,CAAYV,cAAc,CAACgC,OAA3B,EAAoCD,GAApC,CAVa;AAWnBH,YAAAA,YAAY,CAAC7B,GAAD,CAAZ,CAXmB,0DAAH,mBAAZgB,YAAY,qEAAlB;;;AAcA,IAAMD,eAAe,uHAAG;AACtBf,EAAAA,GADsB;AAEtBG,EAAAA,YAFsB;AAGtBF,EAAAA,cAHsB;AAItBS,EAAAA,OAJsB;AAKtBI,EAAAA,MALsB;;AAOhBoB,YAAAA,UAPgB,GAOH,mBAAU/B,YAAV,CAPG;AAQtB+B,YAAAA,UAAU,CAACpB,MAAX,GAAoBA,MAApB;AACAoB,YAAAA,UAAU,CAACxB,OAAX,GAAqBA,OAAO,EAA5B,CATsB;AAUhBV,cAAAA,GAAG,CAACW,OAAJ,CAAYV,cAAc,CAACkC,UAA3B,EAAuCD,UAAvC,CAVgB;AAWtBL,YAAAA,YAAY,CAAC7B,GAAD,CAAZ,CAXsB;AAYfc,YAAAA,MAZe,4DAAH,mBAAfC,eAAe,yEAArB,C;;;AAeehB,U","sourcesContent":["import { cloneDeep, isUndefined } from \"lodash/fp\"\nimport { generate } from \"shortid\"\nimport { UnauthorisedError } from \"./errors\"\n\nexport const apiWrapper = async (\n app,\n eventNamespace,\n isAuthorized,\n eventContext,\n func,\n ...params\n) => {\n pushCallStack(app, eventNamespace)\n\n if (!isAuthorized(app)) {\n handleNotAuthorized(app, eventContext, eventNamespace)\n return\n }\n\n const startDate = Date.now()\n const elapsed = () => Date.now() - startDate\n\n try {\n await app.publish(eventNamespace.onBegin, eventContext)\n\n const result = await func(...params)\n\n await publishComplete(app, eventContext, eventNamespace, elapsed, result)\n return result\n } catch (error) {\n await publishError(app, eventContext, eventNamespace, elapsed, error)\n throw error\n }\n}\n\nexport const apiWrapperSync = (\n app,\n eventNamespace,\n isAuthorized,\n eventContext,\n func,\n ...params\n) => {\n pushCallStack(app, eventNamespace)\n\n if (!isAuthorized(app)) {\n handleNotAuthorized(app, eventContext, eventNamespace)\n return\n }\n\n const startDate = Date.now()\n const elapsed = () => Date.now() - startDate\n\n try {\n app.publish(eventNamespace.onBegin, eventContext)\n\n const result = func(...params)\n\n publishComplete(app, eventContext, eventNamespace, elapsed, result)\n return result\n } catch (error) {\n publishError(app, eventContext, eventNamespace, elapsed, error)\n throw error\n }\n}\n\nconst handleNotAuthorized = (app, eventContext, eventNamespace) => {\n const err = new UnauthorisedError(`Unauthorized: ${eventNamespace}`)\n publishError(app, eventContext, eventNamespace, () => 0, err)\n throw err\n}\n\nconst pushCallStack = (app, eventNamespace, seedCallId) => {\n const callId = generate()\n\n const createCallStack = () => ({\n seedCallId: !isUndefined(seedCallId) ? seedCallId : callId,\n threadCallId: callId,\n stack: [],\n })\n\n if (isUndefined(app.calls)) {\n app.calls = createCallStack()\n }\n\n app.calls.stack.push({\n namespace: eventNamespace,\n callId,\n })\n}\n\nconst popCallStack = app => {\n app.calls.stack.pop()\n if (app.calls.stack.length === 0) {\n delete app.calls\n }\n}\n\nconst publishError = async (\n app,\n eventContext,\n eventNamespace,\n elapsed,\n err\n) => {\n const ctx = cloneDeep(eventContext)\n ctx.error = err\n ctx.elapsed = elapsed()\n await app.publish(eventNamespace.onError, ctx)\n popCallStack(app)\n}\n\nconst publishComplete = async (\n app,\n eventContext,\n eventNamespace,\n elapsed,\n result\n) => {\n const endcontext = cloneDeep(eventContext)\n endcontext.result = result\n endcontext.elapsed = elapsed()\n await app.publish(eventNamespace.onComplete, endcontext)\n popCallStack(app)\n return result\n}\n\nexport default apiWrapper\n"],"file":"apiWrapper.js"} \ No newline at end of file +{"version":3,"sources":["../../src/common/apiWrapper.js"],"names":["apiWrapper","app","eventNamespace","isAuthorized","eventContext","func","pushCallStack","handleNotAuthorized","startDate","Date","now","elapsed","publish","onBegin","params","result","publishComplete","publishError","apiWrapperSync","error","err","UnauthorisedError","seedCallId","callId","createCallStack","threadCallId","stack","calls","push","namespace","popCallStack","pop","length","ctx","onError","endcontext","onComplete"],"mappings":"+ZAAA;AACA;AACA;;AAEO,IAAMA,UAAU,sHAAG;AACxBC,EAAAA,GADwB;AAExBC,EAAAA,cAFwB;AAGxBC,EAAAA,YAHwB;AAIxBC,EAAAA,YAJwB;AAKxBC,EAAAA,IALwB;;;AAQxBC,YAAAA,aAAa,CAACL,GAAD,EAAMC,cAAN,CAAb,CARwB;;AAUnBC,YAAAA,YAAY,CAACF,GAAD,CAVO;AAWtBM,YAAAA,mBAAmB,CAACN,GAAD,EAAMG,YAAN,EAAoBF,cAApB,CAAnB,CAXsB;;;;AAelBM,YAAAA,SAfkB,GAeNC,IAAI,CAACC,GAAL,EAfM;AAgBlBC,YAAAA,OAhBkB,GAgBR,SAAVA,OAAU,WAAMF,IAAI,CAACC,GAAL,KAAaF,SAAnB,EAhBQ;;;AAmBhBP,cAAAA,GAAG,CAACW,OAAJ,CAAYV,cAAc,CAACW,OAA3B,EAAoCT,YAApC,CAnBgB,mCAMrBU,MANqB,uEAMrBA,MANqB;;AAqBDT,cAAAA,IAAI,MAAJ,SAAQS,MAAR,CArBC,UAqBhBC,MArBgB;;AAuBhBC,cAAAA,eAAe,CAACf,GAAD,EAAMG,YAAN,EAAoBF,cAApB,EAAoCS,OAApC,EAA6CI,MAA7C,CAvBC;AAwBfA,YAAAA,MAxBe;;AA0BhBE,cAAAA,YAAY,CAAChB,GAAD,EAAMG,YAAN,EAAoBF,cAApB,EAAoCS,OAApC,cA1BI,sGAAH,mBAAVX,UAAU,kEAAhB,C;;;;;AA+BA,IAAMkB,cAAc,GAAG,SAAjBA,cAAiB;AAC5BjB,GAD4B;AAE5BC,cAF4B;AAG5BC,YAH4B;AAI5BC,YAJ4B;AAK5BC,IAL4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,eAAe,uHAAG;AACtBf,EAAAA,GADsB;AAEtBG,EAAAA,YAFsB;AAGtBF,EAAAA,cAHsB;AAItBS,EAAAA,OAJsB;AAKtBI,EAAAA,MALsB;;AAOhBoB,YAAAA,UAPgB,GAOH,mBAAU/B,YAAV,CAPG;AAQtB+B,YAAAA,UAAU,CAACpB,MAAX,GAAoBA,MAApB;AACAoB,YAAAA,UAAU,CAACxB,OAAX,GAAqBA,OAAO,EAA5B,CATsB;AAUhBV,cAAAA,GAAG,CAACW,OAAJ,CAAYV,cAAc,CAACkC,UAA3B,EAAuCD,UAAvC,CAVgB;AAWtBL,YAAAA,YAAY,CAAC7B,GAAD,CAAZ,CAXsB;AAYfc,YAAAA,MAZe,4DAAH,mBAAfC,eAAe,yEAArB,C;;;AAeehB,U","sourcesContent":["import { cloneDeep, isUndefined } from \"lodash/fp\"\r\nimport { generate } from \"shortid\"\r\nimport { UnauthorisedError } from \"./errors\"\r\n\r\nexport const apiWrapper = async (\r\n app,\r\n eventNamespace,\r\n isAuthorized,\r\n eventContext,\r\n func,\r\n ...params\r\n) => {\r\n pushCallStack(app, eventNamespace)\r\n\r\n if (!isAuthorized(app)) {\r\n handleNotAuthorized(app, eventContext, eventNamespace)\r\n return\r\n }\r\n\r\n const startDate = Date.now()\r\n const elapsed = () => Date.now() - startDate\r\n\r\n try {\r\n await app.publish(eventNamespace.onBegin, eventContext)\r\n\r\n const result = await func(...params)\r\n\r\n await publishComplete(app, eventContext, eventNamespace, elapsed, result)\r\n return result\r\n } catch (error) {\r\n await publishError(app, eventContext, eventNamespace, elapsed, error)\r\n throw error\r\n }\r\n}\r\n\r\nexport const apiWrapperSync = (\r\n app,\r\n eventNamespace,\r\n isAuthorized,\r\n eventContext,\r\n func,\r\n ...params\r\n) => {\r\n pushCallStack(app, eventNamespace)\r\n\r\n if (!isAuthorized(app)) {\r\n handleNotAuthorized(app, eventContext, eventNamespace)\r\n return\r\n }\r\n\r\n const startDate = Date.now()\r\n const elapsed = () => Date.now() - startDate\r\n\r\n try {\r\n app.publish(eventNamespace.onBegin, eventContext)\r\n\r\n const result = func(...params)\r\n\r\n publishComplete(app, eventContext, eventNamespace, elapsed, result)\r\n return result\r\n } catch (error) {\r\n publishError(app, eventContext, eventNamespace, elapsed, error)\r\n throw error\r\n }\r\n}\r\n\r\nconst handleNotAuthorized = (app, eventContext, eventNamespace) => {\r\n const err = new UnauthorisedError(`Unauthorized: ${eventNamespace}`)\r\n publishError(app, eventContext, eventNamespace, () => 0, err)\r\n throw err\r\n}\r\n\r\nconst pushCallStack = (app, eventNamespace, seedCallId) => {\r\n const callId = generate()\r\n\r\n const createCallStack = () => ({\r\n seedCallId: !isUndefined(seedCallId) ? seedCallId : callId,\r\n threadCallId: callId,\r\n stack: [],\r\n })\r\n\r\n if (isUndefined(app.calls)) {\r\n app.calls = createCallStack()\r\n }\r\n\r\n app.calls.stack.push({\r\n namespace: eventNamespace,\r\n callId,\r\n })\r\n}\r\n\r\nconst popCallStack = app => {\r\n app.calls.stack.pop()\r\n if (app.calls.stack.length === 0) {\r\n delete app.calls\r\n }\r\n}\r\n\r\nconst publishError = async (\r\n app,\r\n eventContext,\r\n eventNamespace,\r\n elapsed,\r\n err\r\n) => {\r\n const ctx = cloneDeep(eventContext)\r\n ctx.error = err\r\n ctx.elapsed = elapsed()\r\n await app.publish(eventNamespace.onError, ctx)\r\n popCallStack(app)\r\n}\r\n\r\nconst publishComplete = async (\r\n app,\r\n eventContext,\r\n eventNamespace,\r\n elapsed,\r\n result\r\n) => {\r\n const endcontext = cloneDeep(eventContext)\r\n endcontext.result = result\r\n endcontext.elapsed = elapsed()\r\n await app.publish(eventNamespace.onComplete, endcontext)\r\n popCallStack(app)\r\n return result\r\n}\r\n\r\nexport default apiWrapper\r\n"],"file":"apiWrapper.js"} \ No newline at end of file diff --git a/packages/common/lib/common/compileCode.js.map b/packages/common/lib/common/compileCode.js.map index f32cc0ab6c..4004d3743a 100644 --- a/packages/common/lib/common/compileCode.js.map +++ b/packages/common/lib/common/compileCode.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/common/compileCode.js"],"names":["compileCode","code","func","safeCode","trimmed","trim","endsWith","substring","length","e","message"],"mappings":"wGAAA;AACA;;AAEO,IAAMA,WAAW,GAAG,SAAdA,WAAc,CAAAC,IAAI,EAAI;AACjC,MAAIC,IAAJ;AACA,MAAIC,QAAJ;;AAEA,MAAI,kBAAS,SAAT,EAAoBF,IAApB,CAAJ,EAA+B;AAC7BE,IAAAA,QAAQ,GAAGF,IAAX;AACD,GAFD,MAEO;AACL,QAAIG,OAAO,GAAGH,IAAI,CAACI,IAAL,EAAd;AACAD,IAAAA,OAAO,GAAGA,OAAO,CAACE,QAAR,CAAiB,GAAjB;AACNF,IAAAA,OAAO,CAACG,SAAR,CAAkB,CAAlB,EAAqBH,OAAO,CAACI,MAAR,GAAiB,CAAtC,CADM;AAENJ,IAAAA,OAFJ;AAGAD,IAAAA,QAAQ,qBAAcC,OAAd,MAAR;AACD;;AAED,MAAI;AACFF,IAAAA,IAAI,GAAG,+BAAMC,QAAN,CAAP;AACD,GAFD,CAEE,OAAOM,CAAP,EAAU;AACVA,IAAAA,CAAC,CAACC,OAAF,oCAAsCT,IAAtC,gBAAgDQ,CAAC,CAACC,OAAlD;AACA,UAAMD,CAAN;AACD;;AAED,SAAOP,IAAP;AACD,CAtBM,C","sourcesContent":["import { compileCode as cCode } from \"@nx-js/compiler-util\"\nimport { includes } from \"lodash/fp\"\n\nexport const compileCode = code => {\n let func\n let safeCode\n\n if (includes(\"return \")(code)) {\n safeCode = code\n } else {\n let trimmed = code.trim()\n trimmed = trimmed.endsWith(\";\")\n ? trimmed.substring(0, trimmed.length - 1)\n : trimmed\n safeCode = `return (${trimmed})`\n }\n\n try {\n func = cCode(safeCode)\n } catch (e) {\n e.message = `Error compiling code : ${code} : ${e.message}`\n throw e\n }\n\n return func\n}\n"],"file":"compileCode.js"} \ No newline at end of file +{"version":3,"sources":["../../src/common/compileCode.js"],"names":["compileCode","code","func","safeCode","trimmed","trim","endsWith","substring","length","e","message"],"mappings":"wGAAA;AACA;;AAEO,IAAMA,WAAW,GAAG,SAAdA,WAAc,CAAAC,IAAI,EAAI;AACjC,MAAIC,IAAJ;AACA,MAAIC,QAAJ;;AAEA,MAAI,kBAAS,SAAT,EAAoBF,IAApB,CAAJ,EAA+B;AAC7BE,IAAAA,QAAQ,GAAGF,IAAX;AACD,GAFD,MAEO;AACL,QAAIG,OAAO,GAAGH,IAAI,CAACI,IAAL,EAAd;AACAD,IAAAA,OAAO,GAAGA,OAAO,CAACE,QAAR,CAAiB,GAAjB;AACNF,IAAAA,OAAO,CAACG,SAAR,CAAkB,CAAlB,EAAqBH,OAAO,CAACI,MAAR,GAAiB,CAAtC,CADM;AAENJ,IAAAA,OAFJ;AAGAD,IAAAA,QAAQ,qBAAcC,OAAd,MAAR;AACD;;AAED,MAAI;AACFF,IAAAA,IAAI,GAAG,+BAAMC,QAAN,CAAP;AACD,GAFD,CAEE,OAAOM,CAAP,EAAU;AACVA,IAAAA,CAAC,CAACC,OAAF,oCAAsCT,IAAtC,gBAAgDQ,CAAC,CAACC,OAAlD;AACA,UAAMD,CAAN;AACD;;AAED,SAAOP,IAAP;AACD,CAtBM,C","sourcesContent":["import { compileCode as cCode } from \"@nx-js/compiler-util\"\r\nimport { includes } from \"lodash/fp\"\r\n\r\nexport const compileCode = code => {\r\n let func\r\n let safeCode\r\n\r\n if (includes(\"return \")(code)) {\r\n safeCode = code\r\n } else {\r\n let trimmed = code.trim()\r\n trimmed = trimmed.endsWith(\";\")\r\n ? trimmed.substring(0, trimmed.length - 1)\r\n : trimmed\r\n safeCode = `return (${trimmed})`\r\n }\r\n\r\n try {\r\n func = cCode(safeCode)\r\n } catch (e) {\r\n e.message = `Error compiling code : ${code} : ${e.message}`\r\n throw e\r\n }\r\n\r\n return func\r\n}\r\n"],"file":"compileCode.js"} \ No newline at end of file diff --git a/packages/common/lib/common/errors.js.map b/packages/common/lib/common/errors.js.map index 833284900a..c39f05df0f 100644 --- a/packages/common/lib/common/errors.js.map +++ b/packages/common/lib/common/errors.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/common/errors.js"],"names":["BadRequestError","message","httpStatusCode","Error","UnauthorisedError","ForbiddenError","NotFoundError","ConflictError"],"mappings":"i9CAAaA,e;AACX,2BAAYC,OAAZ,EAAqB;AACnB,8BAAMA,OAAN;AACA,UAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,yEAJkCC,K;;;AAOxBC,iB;AACX,6BAAYH,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,2EAJoCC,K;;;AAO1BE,c;AACX,0BAAYJ,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,wEAJiCC,K;;;AAOvBG,a;AACX,yBAAYL,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,uEAJgCC,K;;;AAOtBI,a;AACX,yBAAYN,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,uEAJgCC,K","sourcesContent":["export class BadRequestError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 400\n }\n}\n\nexport class UnauthorisedError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 401\n }\n}\n\nexport class ForbiddenError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 403\n }\n}\n\nexport class NotFoundError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 404\n }\n}\n\nexport class ConflictError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 409\n }\n}\n"],"file":"errors.js"} \ No newline at end of file +{"version":3,"sources":["../../src/common/errors.js"],"names":["BadRequestError","message","httpStatusCode","Error","UnauthorisedError","ForbiddenError","NotFoundError","ConflictError"],"mappings":"i9CAAaA,e;AACX,2BAAYC,OAAZ,EAAqB;AACnB,8BAAMA,OAAN;AACA,UAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,yEAJkCC,K;;;AAOxBC,iB;AACX,6BAAYH,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,2EAJoCC,K;;;AAO1BE,c;AACX,0BAAYJ,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,wEAJiCC,K;;;AAOvBG,a;AACX,yBAAYL,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,uEAJgCC,K;;;AAOtBI,a;AACX,yBAAYN,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,uEAJgCC,K","sourcesContent":["export class BadRequestError extends Error {\r\n constructor(message) {\r\n super(message)\r\n this.httpStatusCode = 400\r\n }\r\n}\r\n\r\nexport class UnauthorisedError extends Error {\r\n constructor(message) {\r\n super(message)\r\n this.httpStatusCode = 401\r\n }\r\n}\r\n\r\nexport class ForbiddenError extends Error {\r\n constructor(message) {\r\n super(message)\r\n this.httpStatusCode = 403\r\n }\r\n}\r\n\r\nexport class NotFoundError extends Error {\r\n constructor(message) {\r\n super(message)\r\n this.httpStatusCode = 404\r\n }\r\n}\r\n\r\nexport class ConflictError extends Error {\r\n constructor(message) {\r\n super(message)\r\n this.httpStatusCode = 409\r\n }\r\n}\r\n"],"file":"errors.js"} \ No newline at end of file diff --git a/packages/common/lib/common/eventAggregator.js.map b/packages/common/lib/common/eventAggregator.js.map index 8c8719202d..3dd9e6d67b 100644 --- a/packages/common/lib/common/eventAggregator.js.map +++ b/packages/common/lib/common/eventAggregator.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/common/eventAggregator.js"],"names":["publish","handlers","eventName","context","handler","subscribe","push","createEventAggregator","eventAggregator"],"mappings":"iZAAA,+B;;AAEA,IAAMA,OAAO,GAAG,SAAVA,OAAU,CAAAC,QAAQ,6HAAI,iBAAOC,SAAP,oLAAkBC,OAAlB,2DAA4B,EAA5B;AACrB,2BAAID,SAAJ,EAAeD,QAAf,CADqB;;AAGJA,cAAAA,QAAQ,CAACC,SAAD,CAHJ,sGAGfE,OAHe;AAIlBA,gBAAAA,OAAO,CAACF,SAAD,EAAYC,OAAZ,CAJW,gTAAJ,mEAAxB;;;;AAQA,IAAME,SAAS,GAAG,SAAZA,SAAY,CAAAJ,QAAQ,UAAI,UAACC,SAAD,EAAYE,OAAZ,EAAwB;AACpD,QAAI,CAAC,aAAIF,SAAJ,EAAeD,QAAf,CAAL,EAA+B;AAC7BA,MAAAA,QAAQ,CAACC,SAAD,CAAR,GAAsB,EAAtB;AACD;AACDD,IAAAA,QAAQ,CAACC,SAAD,CAAR,CAAoBI,IAApB,CAAyBF,OAAzB;AACD,GALyB,EAA1B;;AAOO,IAAMG,qBAAqB,GAAG,SAAxBA,qBAAwB,GAAM;AACzC,MAAMN,QAAQ,GAAG,EAAjB;AACA,MAAMO,eAAe,GAAG;AACtBR,IAAAA,OAAO,EAAEA,OAAO,CAACC,QAAD,CADM;AAEtBI,IAAAA,SAAS,EAAEA,SAAS,CAACJ,QAAD,CAFE,EAAxB;;AAIA,SAAOO,eAAP;AACD,CAPM,C;;AASQD,qB","sourcesContent":["import { has } from \"lodash/fp\"\n\nconst publish = handlers => async (eventName, context = {}) => {\n if (!has(eventName)(handlers)) return\n\n for (const handler of handlers[eventName]) {\n await handler(eventName, context)\n }\n}\n\nconst subscribe = handlers => (eventName, handler) => {\n if (!has(eventName)(handlers)) {\n handlers[eventName] = []\n }\n handlers[eventName].push(handler)\n}\n\nexport const createEventAggregator = () => {\n const handlers = {}\n const eventAggregator = {\n publish: publish(handlers),\n subscribe: subscribe(handlers),\n }\n return eventAggregator\n}\n\nexport default createEventAggregator\n"],"file":"eventAggregator.js"} \ No newline at end of file +{"version":3,"sources":["../../src/common/eventAggregator.js"],"names":["publish","handlers","eventName","context","handler","subscribe","push","createEventAggregator","eventAggregator"],"mappings":"iZAAA,+B;;AAEA,IAAMA,OAAO,GAAG,SAAVA,OAAU,CAAAC,QAAQ,6HAAI,iBAAOC,SAAP,oLAAkBC,OAAlB,2DAA4B,EAA5B;AACrB,2BAAID,SAAJ,EAAeD,QAAf,CADqB;;AAGJA,cAAAA,QAAQ,CAACC,SAAD,CAHJ,sGAGfE,OAHe;AAIlBA,gBAAAA,OAAO,CAACF,SAAD,EAAYC,OAAZ,CAJW,gTAAJ,mEAAxB;;;;AAQA,IAAME,SAAS,GAAG,SAAZA,SAAY,CAAAJ,QAAQ,UAAI,UAACC,SAAD,EAAYE,OAAZ,EAAwB;AACpD,QAAI,CAAC,aAAIF,SAAJ,EAAeD,QAAf,CAAL,EAA+B;AAC7BA,MAAAA,QAAQ,CAACC,SAAD,CAAR,GAAsB,EAAtB;AACD;AACDD,IAAAA,QAAQ,CAACC,SAAD,CAAR,CAAoBI,IAApB,CAAyBF,OAAzB;AACD,GALyB,EAA1B;;AAOO,IAAMG,qBAAqB,GAAG,SAAxBA,qBAAwB,GAAM;AACzC,MAAMN,QAAQ,GAAG,EAAjB;AACA,MAAMO,eAAe,GAAG;AACtBR,IAAAA,OAAO,EAAEA,OAAO,CAACC,QAAD,CADM;AAEtBI,IAAAA,SAAS,EAAEA,SAAS,CAACJ,QAAD,CAFE,EAAxB;;AAIA,SAAOO,eAAP;AACD,CAPM,C;;AASQD,qB","sourcesContent":["import { has } from \"lodash/fp\"\r\n\r\nconst publish = handlers => async (eventName, context = {}) => {\r\n if (!has(eventName)(handlers)) return\r\n\r\n for (const handler of handlers[eventName]) {\r\n await handler(eventName, context)\r\n }\r\n}\r\n\r\nconst subscribe = handlers => (eventName, handler) => {\r\n if (!has(eventName)(handlers)) {\r\n handlers[eventName] = []\r\n }\r\n handlers[eventName].push(handler)\r\n}\r\n\r\nexport const createEventAggregator = () => {\r\n const handlers = {}\r\n const eventAggregator = {\r\n publish: publish(handlers),\r\n subscribe: subscribe(handlers),\r\n }\r\n return eventAggregator\r\n}\r\n\r\nexport default createEventAggregator\r\n"],"file":"eventAggregator.js"} \ No newline at end of file diff --git a/packages/common/lib/common/events.js.map b/packages/common/lib/common/events.js.map index edf1c04791..f290ec2c42 100644 --- a/packages/common/lib/common/events.js.map +++ b/packages/common/lib/common/events.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/common/events.js"],"names":["commonPlus","extra","common","_events","recordApi","save","getContext","getNew","load","validate","uploadFile","downloadFile","indexApi","buildIndex","listItems","aggregates","collectionApi","getAllowedRecordTypes","initialise","authApi","authenticate","authenticateTemporaryAccess","createTemporaryAccess","createUser","enableUser","disableUser","loadAccessLevels","getNewAccessLevel","getNewUser","getNewUserAuth","getUsers","saveAccessLevels","isAuthorized","changeMyPassword","setPasswordFromTemporaryCode","scorePassword","isValidPassword","validateUser","validateAccessLevels","setUserAccessLevels","templateApi","saveApplicationHierarchy","saveActionsAndTriggers","actionsApi","execute","_eventsList","makeEvent","area","method","name","areaKey","methodKey","obj","s","push","events","eventsList"],"mappings":"6IAAA;;AAEA,IAAMA,UAAU,GAAG,SAAbA,UAAa,CAAAC,KAAK,UAAI,eAAM,CAAC,SAAD,EAAY,YAAZ,EAA0B,SAA1B,CAAN,EAA4CA,KAA5C,CAAJ,EAAxB;;AAEA,IAAMC,MAAM,GAAG,SAATA,MAAS,WAAMF,UAAU,CAAC,EAAD,CAAhB,EAAf;;AAEA,IAAMG,OAAO,GAAG;AACdC,EAAAA,SAAS,EAAE;AACTC,IAAAA,IAAI,EAAEL,UAAU,CAAC,CAAC,WAAD,EAAc,iBAAd,EAAiC,iBAAjC,CAAD,CADP;AAET,cAAQE,MAAM,EAFL;AAGTI,IAAAA,UAAU,EAAEJ,MAAM,EAHT;AAITK,IAAAA,M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AC+C,QAAD,CAAP,CAAiBC,SAAjB,CAAnB,EAAgD;AAC9CN,MAAAA,WAAW,CAACS,IAAZ,CAAiBnD,OAAO,CAAC+C,QAAD,CAAP,CAAiBC,SAAjB,EAA4BF,IAA5B,CAAjB;AACD;AACF;AACF;;AAEM,IAAMM,MAAM,GAAGpD,OAAf,C;;AAEA,IAAMqD,UAAU,GAAGX,WAAnB,C;;AAEQ,EAAEU,MAAM,EAAEpD,OAAV,EAAmBqD,UAAU,EAAEX,WAA/B,E","sourcesContent":["import { union, reduce } from \"lodash/fp\"\n\nconst commonPlus = extra => union([\"onBegin\", \"onComplete\", \"onError\"])(extra)\n\nconst common = () => commonPlus([])\n\nconst _events = {\n recordApi: {\n save: commonPlus([\"onInvalid\", \"onRecordUpdated\", \"onRecordCreated\"]),\n delete: common(),\n getContext: common(),\n getNew: common(),\n load: common(),\n validate: common(),\n uploadFile: common(),\n downloadFile: common(),\n },\n indexApi: {\n buildIndex: common(),\n listItems: common(),\n delete: common(),\n aggregates: common(),\n },\n collectionApi: {\n getAllowedRecordTypes: common(),\n initialise: common(),\n delete: common(),\n },\n authApi: {\n authenticate: common(),\n authenticateTemporaryAccess: common(),\n createTemporaryAccess: common(),\n createUser: common(),\n enableUser: common(),\n disableUser: common(),\n loadAccessLevels: common(),\n getNewAccessLevel: common(),\n getNewUser: common(),\n getNewUserAuth: common(),\n getUsers: common(),\n saveAccessLevels: common(),\n isAuthorized: common(),\n changeMyPassword: common(),\n setPasswordFromTemporaryCode: common(),\n scorePassword: common(),\n isValidPassword: common(),\n validateUser: common(),\n validateAccessLevels: common(),\n setUserAccessLevels: common(),\n },\n templateApi: {\n saveApplicationHierarchy: common(),\n saveActionsAndTriggers: common(),\n },\n actionsApi: {\n execute: common(),\n },\n}\n\nconst _eventsList = []\n\nconst makeEvent = (area, method, name) => `${area}:${method}:${name}`\n\nfor (const areaKey in _events) {\n for (const methodKey in _events[areaKey]) {\n _events[areaKey][methodKey] = reduce((obj, s) => {\n obj[s] = makeEvent(areaKey, methodKey, s)\n return obj\n }, {})(_events[areaKey][methodKey])\n }\n}\n\nfor (const areaKey in _events) {\n for (const methodKey in _events[areaKey]) {\n for (const name in _events[areaKey][methodKey]) {\n _eventsList.push(_events[areaKey][methodKey][name])\n }\n }\n}\n\nexport const events = _events\n\nexport const eventsList = _eventsList\n\nexport default { events: _events, eventsList: _eventsList }\n"],"file":"events.js"} \ No newline at end of file +{"version":3,"sources":["../../src/common/events.js"],"names":["commonPlus","extra","common","_events","recordApi","save","getContext","getNew","load","validate","uploadFile","downloadFile","indexApi","buildIndex","listItems","aggregates","collectionApi","getAllowedRecordTypes","initialise","authApi","authenticate","authenticateTemporaryAccess","createTemporaryAccess","createUser","enableUser","disableUser","loadAccessLevels","getNewAccessLevel","getNewUser","getNewUserAuth","getUsers","saveAccessLevels","isAuthorized","changeMyPassword","setPasswordFromTemporaryCode","scorePassword","isValidPassword","validateUser","validateAccessLevels","setUserAccessLevels","templateApi","saveApplicationHierarchy","saveActionsAndTriggers","actionsApi","execute","_eventsList","makeEvent","area","method","name","areaKey","methodKey","obj","s","push","events","eventsList"],"mappings":"6IAAA;;AAEA,IAAMA,UAAU,GAAG,SAAbA,UAAa,CAAAC,KAAK,UAAI,eAAM,CAAC,SAAD,EAAY,YAAZ,EAA0B,SAA1B,CAAN,EAA4CA,KAA5C,CAAJ,EAAxB;;AAEA,IAAMC,MAAM,GAAG,SAATA,MAAS,WAAMF,UAAU,CAAC,EAAD,CAAhB,EAAf;;AAEA,IAAMG,OAAO,GAAG;AACdC,EAAAA,SAAS,EAAE;AACTC,IAAAA,IAAI,EAAEL,UAAU,CAAC,CAAC,WAAD,EAAc,iBAAd,EAAiC,iBAAjC,CAAD,CADP;AAET,cAAQE,MAAM,EAFL;AAGTI,IAAAA,UAAU,EAAEJ,MAAM,EAHT;AAITK,IAAAA,MAAM,EAAEL,MAAM,EAJL;AAKTM,IAAAA,IAAI,EAAEN,MAAM,EALH;AAMTO,IAAAA,QAAQ,E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AiBnD,OAAO,CAAC+C,QAAD,CAAP,CAAiBC,SAAjB,EAA4BF,IAA5B,CAAjB;AACD;AACF;AACF;;AAEM,IAAMM,MAAM,GAAGpD,OAAf,C;;AAEA,IAAMqD,UAAU,GAAGX,WAAnB,C;;AAEQ,EAAEU,MAAM,EAAEpD,OAAV,EAAmBqD,UAAU,EAAEX,WAA/B,E","sourcesContent":["import { union, reduce } from \"lodash/fp\"\r\n\r\nconst commonPlus = extra => union([\"onBegin\", \"onComplete\", \"onError\"])(extra)\r\n\r\nconst common = () => commonPlus([])\r\n\r\nconst _events = {\r\n recordApi: {\r\n save: commonPlus([\"onInvalid\", \"onRecordUpdated\", \"onRecordCreated\"]),\r\n delete: common(),\r\n getContext: common(),\r\n getNew: common(),\r\n load: common(),\r\n validate: common(),\r\n uploadFile: common(),\r\n downloadFile: common(),\r\n },\r\n indexApi: {\r\n buildIndex: common(),\r\n listItems: common(),\r\n delete: common(),\r\n aggregates: common(),\r\n },\r\n collectionApi: {\r\n getAllowedRecordTypes: common(),\r\n initialise: common(),\r\n delete: common(),\r\n },\r\n authApi: {\r\n authenticate: common(),\r\n authenticateTemporaryAccess: common(),\r\n createTemporaryAccess: common(),\r\n createUser: common(),\r\n enableUser: common(),\r\n disableUser: common(),\r\n loadAccessLevels: common(),\r\n getNewAccessLevel: common(),\r\n getNewUser: common(),\r\n getNewUserAuth: common(),\r\n getUsers: common(),\r\n saveAccessLevels: common(),\r\n isAuthorized: common(),\r\n changeMyPassword: common(),\r\n setPasswordFromTemporaryCode: common(),\r\n scorePassword: common(),\r\n isValidPassword: common(),\r\n validateUser: common(),\r\n validateAccessLevels: common(),\r\n setUserAccessLevels: common(),\r\n },\r\n templateApi: {\r\n saveApplicationHierarchy: common(),\r\n saveActionsAndTriggers: common(),\r\n },\r\n actionsApi: {\r\n execute: common(),\r\n },\r\n}\r\n\r\nconst _eventsList = []\r\n\r\nconst makeEvent = (area, method, name) => `${area}:${method}:${name}`\r\n\r\nfor (const areaKey in _events) {\r\n for (const methodKey in _events[areaKey]) {\r\n _events[areaKey][methodKey] = reduce((obj, s) => {\r\n obj[s] = makeEvent(areaKey, methodKey, s)\r\n return obj\r\n }, {})(_events[areaKey][methodKey])\r\n }\r\n}\r\n\r\nfor (const areaKey in _events) {\r\n for (const methodKey in _events[areaKey]) {\r\n for (const name in _events[areaKey][methodKey]) {\r\n _eventsList.push(_events[areaKey][methodKey][name])\r\n }\r\n }\r\n}\r\n\r\nexport const events = _events\r\n\r\nexport const eventsList = _eventsList\r\n\r\nexport default { events: _events, eventsList: _eventsList }\r\n"],"file":"events.js"} \ No newline at end of file diff --git a/packages/common/lib/common/index.js.map b/packages/common/lib/common/index.js.map index 775e613d7a..b4ce84d9f5 100644 --- a/packages/common/lib/common/index.js.map +++ b/packages/common/lib/common/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/common/index.js"],"names":["$$","funcs","arg","$","keySep","trimKeySep","str","splitByKeySep","safeKey","key","joinKey","strs","paramsOrArray","length","s","toString","splitKey","getDirFomKey","dropRight","p","getFileFromKey","takeRight","head","configFolder","fieldDefinitions","templateDefinitions","appDefinitionFile","dirIndex","folderPath","getIndexKeyFromFileKey","ifExists","val","exists","notExists","getOrDefault","defaultVal","not","func","isDefined","isUndefined","isNonNull","isNull","isNotNaN","isNaN","allTrue","funcArgs","result","conditionFunc","anyTrue","insensitiveEquals","str1","str2","trim","toLowerCase","isSomething","isNothing","isNothingOrEmpty","v","somethingOrGetDefault","getDefaultFunc","somethingOrDefault","mapIfSomethingOrDefault","mapFunc","mapIfSomethingOrBlank","none","predicate","collection","all","isNotEmpty","ob","isAsync","fn","constructor","name","isNonEmptyArray","isArray","isNonEmptyString","isString","tryOr","failFunc","args","apply","_","tryAwaitOr","defineError","errorPrefix","err","message","tryOrIgnore","tryAwaitOrIgnore","causesException","e","executesWithoutException","handleErrorWith","returnValInError","handleErrorWithUndefined","undefined","switchCase","cases","value","nextCase","nextResult","isValue","val1","val2","isOneOf","vals","defaultCase","memberMatches","member","match","obj","StartsWith","searchFor","searchIn","contains","array","getHashCode","hash","i","char","l","charCodeAt","awEx","promise","isSafeInteger","n","Number","MAX_SAFE_INTEGER","toDateOrNull","Date","toBoolOrNull","toNumberOrNull","isArrayOfString","opts","pushAll","target","items","push","pause","duration","Promise","res","setTimeout","retry","retries","delay","then","events","eventsList","toNumber","toDate","toBool"],"mappings":"06DAAA;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;;;;AAkBA,qC;;AAEA;AACO,IAAMA,EAAE,GAAG,SAALA,EAAK,sCAAIC,KAAJ,oDAAIA,KAAJ,iCAAc,UAAAC,GAAG,UAAI,kBAAKD,KAAL,EAAYC,GAAZ,CAAJ,EAAjB,EAAX;;AAEP;gBACO,IAAMC,CAAC,GAAG,SAAJA,CAAI,CAACD,GAAD,EAAMD,KAAN,UAAgBD,EAAE,MAAF,6CAAMC,KAAN,GAAaC,GAAb,CAAhB,EAAV,C;;AAEA,IAAME,MAAM,GAAG,GAAf,C;AACP,IAAMC,UAAU,GAAG,SAAbA,UAAa,CAAAC,GAAG,UAAI,kBAAKA,GAAL,EAAUF,MAAV,CAAJ,EAAtB;AACA,IAAMG,aAAa,GAAG,SAAhBA,aAAgB,CAAAD,GAAG,UAAI,eAAMF,MAAN,EAAcE,GAAd,CAAJ,EAAzB;AACO,IAAME,OAAO,GAAG,SAAVA,OAAU,CAAAC,GAAG;AACxB,mCAAWL,MAAX,SAAoBC,UAAU,CAACI,GAAD,CAA9B,aAA0CL,MAA1C,SAAmDA,MAAnD,GAA6DA,MAA7D,CADwB,GAAnB,C;AAEA,IAAMM,OAAO,GAAG,SAAVA,OAAU,GAAa,oCAATC,IAAS,yDAATA,IAAS;AAClC,MAAMC,aAAa,GAAID,IAAI,CAACE,MAAL,KAAgB,CAAjB,GAAsB,iBAAQF,IAAI,CAAC,CAAD,CAAZ,CAAtB,GAAyCA,IAAI,CAAC,CAAD,CAA7C,GAAmDA,IAAzE;AACA,SAAOR,CAAC,CAACS,aA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sDbC,EAAAA,MAAM,EAAEtB,YAtDK;AAuDbuB,EAAAA,MAAM,EAAErB,YAvDK;AAwDbE,EAAAA,eAAe,EAAfA,eAxDa;AAyDbpF,EAAAA,iBAAiB,EAAjBA,iBAzDa;AA0Db0F,EAAAA,KAAK,EAALA,KA1Da;AA2DbK,EAAAA,KAAK,EAALA,KA3Da;AA4DbT,EAAAA,OAAO,EAAPA,OA5Da,E","sourcesContent":["import {\n head,\n tail,\n findIndex,\n startsWith,\n dropRight,\n flow,\n takeRight,\n trim,\n replace,\n} from \"lodash\"\nimport {\n some,\n reduce,\n isEmpty,\n isArray,\n join,\n isString,\n isInteger,\n isDate,\n toNumber,\n isUndefined,\n isNaN,\n isNull,\n constant,\n split,\n includes,\n filter,\n} from \"lodash/fp\"\nimport { events, eventsList } from \"./events.js\"\n\n// this is the combinator function\nexport const $$ = (...funcs) => arg => flow(funcs)(arg)\n\n// this is the pipe function\nexport const $ = (arg, funcs) => $$(...funcs)(arg)\n\nexport const keySep = \"/\"\nconst trimKeySep = str => trim(str, keySep)\nconst splitByKeySep = str => split(keySep)(str)\nexport const safeKey = key =>\n replace(`${keySep}${trimKeySep(key)}`, `${keySep}${keySep}`, keySep)\nexport const joinKey = (...strs) => {\n const paramsOrArray = (strs.length === 1) & isArray(strs[0]) ? strs[0] : strs\n return $(paramsOrArray, [\n filter(s => !isUndefined(s) && !isNull(s) && s.toString().length > 0),\n join(keySep),\n safeKey,\n ])\n}\nexport const splitKey = $$(trimKeySep, splitByKeySep)\nexport const getDirFomKey = $$(splitKey, dropRight, p => joinKey(...p))\nexport const getFileFromKey = $$(splitKey, takeRight, head)\n\nexport const configFolder = `${keySep}.config`\nexport const fieldDefinitions = joinKey(configFolder, \"fields.json\")\nexport const templateDefinitions = joinKey(configFolder, \"templates.json\")\nexport const appDefinitionFile = joinKey(configFolder, \"appDefinition.json\")\nexport const dirIndex = folderPath =>\n joinKey(configFolder, \"dir\", ...splitKey(folderPath), \"dir.idx\")\nexport const getIndexKeyFromFileKey = $$(getDirFomKey, dirIndex)\n\nexport const ifExists = (val, exists, notExists) =>\n isUndefined(val)\n ? isUndefined(notExists)\n ? (() => {})()\n : notExists()\n : exists()\n\nexport const getOrDefault = (val, defaultVal) =>\n ifExists(\n val,\n () => val,\n () => defaultVal\n )\n\nexport const not = func => val => !func(val)\nexport const isDefined = not(isUndefined)\nexport const isNonNull = not(isNull)\nexport const isNotNaN = not(isNaN)\n\nexport const allTrue = (...funcArgs) => val =>\n reduce(\n (result, conditionFunc) =>\n (isNull(result) || result == true) && conditionFunc(val),\n null\n )(funcArgs)\n\nexport const anyTrue = (...funcArgs) => val =>\n reduce(\n (result, conditionFunc) => result == true || conditionFunc(val),\n null\n )(funcArgs)\n\nexport const insensitiveEquals = (str1, str2) =>\n str1.trim().toLowerCase() === str2.trim().toLowerCase()\n\nexport const isSomething = allTrue(isDefined, isNonNull, isNotNaN)\nexport const isNothing = not(isSomething)\nexport const isNothingOrEmpty = v => isNothing(v) || isEmpty(v)\nexport const somethingOrGetDefault = getDefaultFunc => val =>\n isSomething(val) ? val : getDefaultFunc()\nexport const somethingOrDefault = (val, defaultVal) =>\n somethingOrGetDefault(constant(defaultVal))(val)\n\nexport const mapIfSomethingOrDefault = (mapFunc, defaultVal) => val =>\n isSomething(val) ? mapFunc(val) : defaultVal\n\nexport const mapIfSomethingOrBlank = mapFunc =>\n mapIfSomethingOrDefault(mapFunc, \"\")\n\nexport const none = predicate => collection => !some(predicate)(collection)\n\nexport const all = predicate => collection =>\n none(v => !predicate(v))(collection)\n\nexport const isNotEmpty = ob => !isEmpty(ob)\nexport const isAsync = fn => fn.constructor.name === \"AsyncFunction\"\nexport const isNonEmptyArray = allTrue(isArray, isNotEmpty)\nexport const isNonEmptyString = allTrue(isString, isNotEmpty)\nexport const tryOr = failFunc => (func, ...args) => {\n try {\n return func.apply(null, ...args)\n } catch (_) {\n return failFunc()\n }\n}\n\nexport const tryAwaitOr = failFunc => async (func, ...args) => {\n try {\n return await func.apply(null, ...args)\n } catch (_) {\n return await failFunc()\n }\n}\n\nexport const defineError = (func, errorPrefix) => {\n try {\n return func()\n } catch (err) {\n err.message = `${errorPrefix} : ${err.message}`\n throw err\n }\n}\n\nexport const tryOrIgnore = tryOr(() => {})\nexport const tryAwaitOrIgnore = tryAwaitOr(async () => {})\nexport const causesException = func => {\n try {\n func()\n return false\n } catch (e) {\n return true\n }\n}\n\nexport const executesWithoutException = func => !causesException(func)\n\nexport const handleErrorWith = returnValInError =>\n tryOr(constant(returnValInError))\n\nexport const handleErrorWithUndefined = handleErrorWith(undefined)\n\nexport const switchCase = (...cases) => value => {\n const nextCase = () => head(cases)[0](value)\n const nextResult = () => head(cases)[1](value)\n\n if (isEmpty(cases)) return // undefined\n if (nextCase() === true) return nextResult()\n return switchCase(...tail(cases))(value)\n}\n\nexport const isValue = val1 => val2 => val1 === val2\nexport const isOneOf = (...vals) => val => includes(val)(vals)\nexport const defaultCase = constant(true)\nexport const memberMatches = (member, match) => obj => match(obj[member])\n\nexport const StartsWith = searchFor => searchIn =>\n startsWith(searchIn, searchFor)\n\nexport const contains = val => array => findIndex(array, v => v === val) > -1\n\nexport const getHashCode = s => {\n let hash = 0\n let i\n let char\n let l\n if (s.length == 0) return hash\n for (i = 0, l = s.length; i < l; i++) {\n char = s.charCodeAt(i)\n hash = (hash << 5) - hash + char\n hash |= 0 // Convert to 32bit integer\n }\n\n // converting to string, but dont want a \"-\" prefixed\n if (hash < 0) {\n return `n${(hash * -1).toString()}`\n }\n return hash.toString()\n}\n\n// thanks to https://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/\nexport const awEx = async promise => {\n try {\n const result = await promise\n return [undefined, result]\n } catch (error) {\n return [error, undefined]\n }\n}\n\nexport const isSafeInteger = n =>\n isInteger(n) &&\n n <= Number.MAX_SAFE_INTEGER &&\n n >= 0 - Number.MAX_SAFE_INTEGER\n\nexport const toDateOrNull = s =>\n isNull(s) ? null : isDate(s) ? s : new Date(s)\nexport const toBoolOrNull = s => (isNull(s) ? null : s === \"true\" || s === true)\nexport const toNumberOrNull = s => (isNull(s) ? null : toNumber(s))\n\nexport const isArrayOfString = opts => isArray(opts) && all(isString)(opts)\n\nexport const pushAll = (target, items) => {\n for (let i of items) target.push(i)\n}\n\nexport const pause = async duration =>\n new Promise(res => setTimeout(res, duration))\n\nexport const retry = async (fn, retries, delay, ...args) => {\n try {\n return await fn(...args)\n } catch (err) {\n if (retries > 1) {\n return await pause(delay).then(\n async () => await retry(fn, retries - 1, delay, ...args)\n )\n }\n throw err\n }\n}\n\nexport { events } from \"./events.js\"\n\nexport default {\n ifExists,\n getOrDefault,\n isDefined,\n isNonNull,\n isNotNaN,\n allTrue,\n isSomething,\n mapIfSomethingOrDefault,\n mapIfSomethingOrBlank,\n configFolder,\n fieldDefinitions,\n isNothing,\n not,\n switchCase,\n defaultCase,\n StartsWith,\n contains,\n templateDefinitions,\n handleErrorWith,\n handleErrorWithUndefined,\n tryOr,\n tryOrIgnore,\n tryAwaitOr,\n tryAwaitOrIgnore,\n dirIndex,\n keySep,\n $,\n $$,\n getDirFomKey,\n getFileFromKey,\n splitKey,\n somethingOrDefault,\n getIndexKeyFromFileKey,\n joinKey,\n somethingOrGetDefault,\n appDefinitionFile,\n isValue,\n all,\n isOneOf,\n memberMatches,\n defineError,\n anyTrue,\n isNonEmptyArray,\n causesException,\n executesWithoutException,\n none,\n getHashCode,\n awEx,\n events,\n eventsList,\n isNothingOrEmpty,\n isSafeInteger,\n toNumber,\n toDate: toDateOrNull,\n toBool: toBoolOrNull,\n isArrayOfString,\n insensitiveEquals,\n pause,\n retry,\n pushAll,\n}\n"],"file":"index.js"} \ No newline at end of file +{"version":3,"sources":["../../src/common/index.js"],"names":["$$","funcs","arg","$","keySep","trimKeySep","str","splitByKeySep","safeKey","key","joinKey","strs","paramsOrArray","length","s","toString","splitKey","getDirFomKey","dropRight","p","getFileFromKey","takeRight","head","configFolder","fieldDefinitions","templateDefinitions","appDefinitionFile","dirIndex","folderPath","getIndexKeyFromFileKey","ifExists","val","exists","notExists","getOrDefault","defaultVal","not","func","isDefined","isUndefined","isNonNull","isNull","isNotNaN","isNaN","allTrue","funcArgs","result","conditionFunc","anyTrue","insensitiveEquals","str1","str2","trim","toLowerCase","isSomething","isNothing","isNothingOrEmpty","v","somethingOrGetDefault","getDefaultFunc","somethingOrDefault","mapIfSomethingOrDefault","mapFunc","mapIfSomethingOrBlank","none","predicate","collection","all","isNotEmpty","ob","isAsync","fn","constructor","name","isNonEmptyArray","isArray","isNonEmptyString","isString","tryOr","failFunc","args","apply","_","tryAwaitOr","defineError","errorPrefix","err","message","tryOrIgnore","tryAwaitOrIgnore","causesException","e","executesWithoutException","handleErrorWith","returnValInError","handleErrorWithUndefined","undefined","switchCase","cases","value","nextCase","nextResult","isValue","val1","val2","isOneOf","vals","defaultCase","memberMatches","member","match","obj","StartsWith","searchFor","searchIn","contains","array","getHashCode","hash","i","char","l","charCodeAt","awEx","promise","isSafeInteger","n","Number","MAX_SAFE_INTEGER","toDateOrNull","Date","toBoolOrNull","toNumberOrNull","isArrayOfString","opts","pushAll","target","items","push","pause","duration","Promise","res","setTimeout","retry","retries","delay","then","events","eventsList","toNumber","toDate","toBool"],"mappings":"06DAAA;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;;;;AAkBA,qC;;AAEA;AACO,IAAMA,EAAE,GAAG,SAALA,EAAK,sCAAIC,KAAJ,oDAAIA,KAAJ,iCAAc,UAAAC,GAAG,UAAI,kBAAKD,KAAL,EAAYC,GAAZ,CAAJ,EAAjB,EAAX;;AAEP;gBACO,IAAMC,CAAC,GAAG,SAAJA,CAAI,CAACD,GAAD,EAAMD,KAAN,UAAgBD,EAAE,MAAF,6CAAMC,KAAN,GAAaC,GAAb,CAAhB,EAAV,C;;AAEA,IAAME,MAAM,GAAG,GAAf,C;AACP,IAAMC,UAAU,GAAG,SAAbA,UAAa,CAAAC,GAAG,UAAI,kBAAKA,GAAL,EAAUF,MAAV,CAAJ,EAAt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aAAa,EAAbA,aAxCa;AAyCbxB,EAAAA,WAAW,EAAXA,WAzCa;AA0CbpC,EAAAA,OAAO,EAAPA,OA1Ca;AA2Cb0B,EAAAA,eAAe,EAAfA,eA3Ca;AA4CbgB,EAAAA,eAAe,EAAfA,eA5Ca;AA6CbE,EAAAA,wBAAwB,EAAxBA,wBA7Ca;AA8Cb5B,EAAAA,IAAI,EAAJA,IA9Ca;AA+CbqD,EAAAA,WAAW,EAAXA,WA/Ca;AAgDbM,EAAAA,IAAI,EAAJA,IAhDa;AAiDbyB,EAAAA,MAAM,EAANA,cAjDa;AAkDbC,EAAAA,UAAU,EAAVA,kBAlDa;AAmDb7F,EAAAA,gBAAgB,EAAhBA,gBAnDa;AAoDbqE,EAAAA,aAAa,EAAbA,aApDa;AAqDbyB,EAAAA,QAAQ,EAARA,YArDa;AAsDbC,EAAAA,MAAM,EAAEtB,YAtDK;AAuDbuB,EAAAA,MAAM,EAAErB,YAvDK;AAwDbE,EAAAA,eAAe,EAAfA,eAxDa;AAyDbpF,EAAAA,iBAAiB,EAAjBA,iBAzDa;AA0Db0F,EAAAA,KAAK,EAALA,KA1Da;AA2DbK,EAAAA,KAAK,EAALA,KA3Da;AA4DbT,EAAAA,OAAO,EAAPA,OA5Da,E","sourcesContent":["import {\r\n head,\r\n tail,\r\n findIndex,\r\n startsWith,\r\n dropRight,\r\n flow,\r\n takeRight,\r\n trim,\r\n replace,\r\n} from \"lodash\"\r\nimport {\r\n some,\r\n reduce,\r\n isEmpty,\r\n isArray,\r\n join,\r\n isString,\r\n isInteger,\r\n isDate,\r\n toNumber,\r\n isUndefined,\r\n isNaN,\r\n isNull,\r\n constant,\r\n split,\r\n includes,\r\n filter,\r\n} from \"lodash/fp\"\r\nimport { events, eventsList } from \"./events.js\"\r\n\r\n// this is the combinator function\r\nexport const $$ = (...funcs) => arg => flow(funcs)(arg)\r\n\r\n// this is the pipe function\r\nexport const $ = (arg, funcs) => $$(...funcs)(arg)\r\n\r\nexport const keySep = \"/\"\r\nconst trimKeySep = str => trim(str, keySep)\r\nconst splitByKeySep = str => split(keySep)(str)\r\nexport const safeKey = key =>\r\n replace(`${keySep}${trimKeySep(key)}`, `${keySep}${keySep}`, keySep)\r\nexport const joinKey = (...strs) => {\r\n const paramsOrArray = (strs.length === 1) & isArray(strs[0]) ? strs[0] : strs\r\n return $(paramsOrArray, [\r\n filter(s => !isUndefined(s) && !isNull(s) && s.toString().length > 0),\r\n join(keySep),\r\n safeKey,\r\n ])\r\n}\r\nexport const splitKey = $$(trimKeySep, splitByKeySep)\r\nexport const getDirFomKey = $$(splitKey, dropRight, p => joinKey(...p))\r\nexport const getFileFromKey = $$(splitKey, takeRight, head)\r\n\r\nexport const configFolder = `${keySep}.config`\r\nexport const fieldDefinitions = joinKey(configFolder, \"fields.json\")\r\nexport const templateDefinitions = joinKey(configFolder, \"templates.json\")\r\nexport const appDefinitionFile = joinKey(configFolder, \"appDefinition.json\")\r\nexport const dirIndex = folderPath =>\r\n joinKey(configFolder, \"dir\", ...splitKey(folderPath), \"dir.idx\")\r\nexport const getIndexKeyFromFileKey = $$(getDirFomKey, dirIndex)\r\n\r\nexport const ifExists = (val, exists, notExists) =>\r\n isUndefined(val)\r\n ? isUndefined(notExists)\r\n ? (() => {})()\r\n : notExists()\r\n : exists()\r\n\r\nexport const getOrDefault = (val, defaultVal) =>\r\n ifExists(\r\n val,\r\n () => val,\r\n () => defaultVal\r\n )\r\n\r\nexport const not = func => val => !func(val)\r\nexport const isDefined = not(isUndefined)\r\nexport const isNonNull = not(isNull)\r\nexport const isNotNaN = not(isNaN)\r\n\r\nexport const allTrue = (...funcArgs) => val =>\r\n reduce(\r\n (result, conditionFunc) =>\r\n (isNull(result) || result == true) && conditionFunc(val),\r\n null\r\n )(funcArgs)\r\n\r\nexport const anyTrue = (...funcArgs) => val =>\r\n reduce(\r\n (result, conditionFunc) => result == true || conditionFunc(val),\r\n null\r\n )(funcArgs)\r\n\r\nexport const insensitiveEquals = (str1, str2) =>\r\n str1.trim().toLowerCase() === str2.trim().toLowerCase()\r\n\r\nexport const isSomething = allTrue(isDefined, isNonNull, isNotNaN)\r\nexport const isNothing = not(isSomething)\r\nexport const isNothingOrEmpty = v => isNothing(v) || isEmpty(v)\r\nexport const somethingOrGetDefault = getDefaultFunc => val =>\r\n isSomething(val) ? val : getDefaultFunc()\r\nexport const somethingOrDefault = (val, defaultVal) =>\r\n somethingOrGetDefault(constant(defaultVal))(val)\r\n\r\nexport const mapIfSomethingOrDefault = (mapFunc, defaultVal) => val =>\r\n isSomething(val) ? mapFunc(val) : defaultVal\r\n\r\nexport const mapIfSomethingOrBlank = mapFunc =>\r\n mapIfSomethingOrDefault(mapFunc, \"\")\r\n\r\nexport const none = predicate => collection => !some(predicate)(collection)\r\n\r\nexport const all = predicate => collection =>\r\n none(v => !predicate(v))(collection)\r\n\r\nexport const isNotEmpty = ob => !isEmpty(ob)\r\nexport const isAsync = fn => fn.constructor.name === \"AsyncFunction\"\r\nexport const isNonEmptyArray = allTrue(isArray, isNotEmpty)\r\nexport const isNonEmptyString = allTrue(isString, isNotEmpty)\r\nexport const tryOr = failFunc => (func, ...args) => {\r\n try {\r\n return func.apply(null, ...args)\r\n } catch (_) {\r\n return failFunc()\r\n }\r\n}\r\n\r\nexport const tryAwaitOr = failFunc => async (func, ...args) => {\r\n try {\r\n return await func.apply(null, ...args)\r\n } catch (_) {\r\n return await failFunc()\r\n }\r\n}\r\n\r\nexport const defineError = (func, errorPrefix) => {\r\n try {\r\n return func()\r\n } catch (err) {\r\n err.message = `${errorPrefix} : ${err.message}`\r\n throw err\r\n }\r\n}\r\n\r\nexport const tryOrIgnore = tryOr(() => {})\r\nexport const tryAwaitOrIgnore = tryAwaitOr(async () => {})\r\nexport const causesException = func => {\r\n try {\r\n func()\r\n return false\r\n } catch (e) {\r\n return true\r\n }\r\n}\r\n\r\nexport const executesWithoutException = func => !causesException(func)\r\n\r\nexport const handleErrorWith = returnValInError =>\r\n tryOr(constant(returnValInError))\r\n\r\nexport const handleErrorWithUndefined = handleErrorWith(undefined)\r\n\r\nexport const switchCase = (...cases) => value => {\r\n const nextCase = () => head(cases)[0](value)\r\n const nextResult = () => head(cases)[1](value)\r\n\r\n if (isEmpty(cases)) return // undefined\r\n if (nextCase() === true) return nextResult()\r\n return switchCase(...tail(cases))(value)\r\n}\r\n\r\nexport const isValue = val1 => val2 => val1 === val2\r\nexport const isOneOf = (...vals) => val => includes(val)(vals)\r\nexport const defaultCase = constant(true)\r\nexport const memberMatches = (member, match) => obj => match(obj[member])\r\n\r\nexport const StartsWith = searchFor => searchIn =>\r\n startsWith(searchIn, searchFor)\r\n\r\nexport const contains = val => array => findIndex(array, v => v === val) > -1\r\n\r\nexport const getHashCode = s => {\r\n let hash = 0\r\n let i\r\n let char\r\n let l\r\n if (s.length == 0) return hash\r\n for (i = 0, l = s.length; i < l; i++) {\r\n char = s.charCodeAt(i)\r\n hash = (hash << 5) - hash + char\r\n hash |= 0 // Convert to 32bit integer\r\n }\r\n\r\n // converting to string, but dont want a \"-\" prefixed\r\n if (hash < 0) {\r\n return `n${(hash * -1).toString()}`\r\n }\r\n return hash.toString()\r\n}\r\n\r\n// thanks to https://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/\r\nexport const awEx = async promise => {\r\n try {\r\n const result = await promise\r\n return [undefined, result]\r\n } catch (error) {\r\n return [error, undefined]\r\n }\r\n}\r\n\r\nexport const isSafeInteger = n =>\r\n isInteger(n) &&\r\n n <= Number.MAX_SAFE_INTEGER &&\r\n n >= 0 - Number.MAX_SAFE_INTEGER\r\n\r\nexport const toDateOrNull = s =>\r\n isNull(s) ? null : isDate(s) ? s : new Date(s)\r\nexport const toBoolOrNull = s => (isNull(s) ? null : s === \"true\" || s === true)\r\nexport const toNumberOrNull = s => (isNull(s) ? null : toNumber(s))\r\n\r\nexport const isArrayOfString = opts => isArray(opts) && all(isString)(opts)\r\n\r\nexport const pushAll = (target, items) => {\r\n for (let i of items) target.push(i)\r\n}\r\n\r\nexport const pause = async duration =>\r\n new Promise(res => setTimeout(res, duration))\r\n\r\nexport const retry = async (fn, retries, delay, ...args) => {\r\n try {\r\n return await fn(...args)\r\n } catch (err) {\r\n if (retries > 1) {\r\n return await pause(delay).then(\r\n async () => await retry(fn, retries - 1, delay, ...args)\r\n )\r\n }\r\n throw err\r\n }\r\n}\r\n\r\nexport { events } from \"./events.js\"\r\n\r\nexport default {\r\n ifExists,\r\n getOrDefault,\r\n isDefined,\r\n isNonNull,\r\n isNotNaN,\r\n allTrue,\r\n isSomething,\r\n mapIfSomethingOrDefault,\r\n mapIfSomethingOrBlank,\r\n configFolder,\r\n fieldDefinitions,\r\n isNothing,\r\n not,\r\n switchCase,\r\n defaultCase,\r\n StartsWith,\r\n contains,\r\n templateDefinitions,\r\n handleErrorWith,\r\n handleErrorWithUndefined,\r\n tryOr,\r\n tryOrIgnore,\r\n tryAwaitOr,\r\n tryAwaitOrIgnore,\r\n dirIndex,\r\n keySep,\r\n $,\r\n $$,\r\n getDirFomKey,\r\n getFileFromKey,\r\n splitKey,\r\n somethingOrDefault,\r\n getIndexKeyFromFileKey,\r\n joinKey,\r\n somethingOrGetDefault,\r\n appDefinitionFile,\r\n isValue,\r\n all,\r\n isOneOf,\r\n memberMatches,\r\n defineError,\r\n anyTrue,\r\n isNonEmptyArray,\r\n causesException,\r\n executesWithoutException,\r\n none,\r\n getHashCode,\r\n awEx,\r\n events,\r\n eventsList,\r\n isNothingOrEmpty,\r\n isSafeInteger,\r\n toNumber,\r\n toDate: toDateOrNull,\r\n toBool: toBoolOrNull,\r\n isArrayOfString,\r\n insensitiveEquals,\r\n pause,\r\n retry,\r\n pushAll,\r\n}\r\n"],"file":"index.js"} \ No newline at end of file diff --git a/packages/common/lib/common/validationCommon.js.map b/packages/common/lib/common/validationCommon.js.map index 421ded1c61..d196a26738 100644 --- a/packages/common/lib/common/validationCommon.js.map +++ b/packages/common/lib/common/validationCommon.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/common/validationCommon.js"],"names":["stringNotEmpty","s","trim","length","makerule","field","error","isValid","validationError","rule","item","applyRuleSet","ruleSet","itemToValidate","applyRule","isSomething","itemTovalidate"],"mappings":"wXAAA;AACA,gC;;AAEO,IAAMA,cAAc,GAAG,SAAjBA,cAAiB,CAAAC,CAAC,UAAI,wBAAYA,CAAZ,KAAkBA,CAAC,CAACC,IAAF,GAASC,MAAT,GAAkB,CAAxC,EAAxB,C;;AAEA,IAAMC,QAAQ,GAAG,SAAXA,QAAW,CAACC,KAAD,EAAQC,KAAR,EAAeC,OAAf,UAA4B,EAAEF,KAAK,EAALA,KAAF,EAASC,KAAK,EAALA,KAAT,EAAgBC,OAAO,EAAPA,OAAhB,EAA5B,EAAjB,C;;AAEA,IAAMC,eAAe,GAAG,SAAlBA,eAAkB,CAACC,IAAD,EAAOC,IAAP,4BAAsBD,IAAtB,IAA4BC,IAAI,EAAJA,IAA5B,KAAxB,C;;AAEA,IAAMC,YAAY,GAAG,SAAfA,YAAe,CAAAC,OAAO,UAAI,UAAAC,cAAc;AACnD,oBAAED,OAAF,EAAW,CAAC,aAAIE,SAAS,CAACD,cAAD,CAAb,CAAD,EAAiC,gBAAOE,kBAAP,CAAjC,CAAX,CADmD,GAAlB,EAA5B,C;;AAGA,IAAMD,SAAS,GAAG,SAAZA,SAAY,CAAAE,cAAc,UAAI,UAAAP,IAAI;AAC7CA,MAAAA,IAAI,CAACF,OAAL,CAAaS,cAAb,IAA+B,IAA/B,GAAsCR,eAAe,CAACC,IAAD,EAAOO,cAAP,CADR,GAAR,EAAhC,C","sourcesContent":["import { filter, map } from \"lodash/fp\"\nimport { $, isSomething } from \"./index\"\n\nexport const stringNotEmpty = s => isSomething(s) && s.trim().length > 0\n\nexport const makerule = (field, error, isValid) => ({ field, error, isValid })\n\nexport const validationError = (rule, item) => ({ ...rule, item })\n\nexport const applyRuleSet = ruleSet => itemToValidate =>\n $(ruleSet, [map(applyRule(itemToValidate)), filter(isSomething)])\n\nexport const applyRule = itemTovalidate => rule =>\n rule.isValid(itemTovalidate) ? null : validationError(rule, itemTovalidate)\n"],"file":"validationCommon.js"} \ No newline at end of file +{"version":3,"sources":["../../src/common/validationCommon.js"],"names":["stringNotEmpty","s","trim","length","makerule","field","error","isValid","validationError","rule","item","applyRuleSet","ruleSet","itemToValidate","applyRule","isSomething","itemTovalidate"],"mappings":"wXAAA;AACA,gC;;AAEO,IAAMA,cAAc,GAAG,SAAjBA,cAAiB,CAAAC,CAAC,UAAI,wBAAYA,CAAZ,KAAkBA,CAAC,CAACC,IAAF,GAASC,MAAT,GAAkB,CAAxC,EAAxB,C;;AAEA,IAAMC,QAAQ,GAAG,SAAXA,QAAW,CAACC,KAAD,EAAQC,KAAR,EAAeC,OAAf,UAA4B,EAAEF,KAAK,EAALA,KAAF,EAASC,KAAK,EAALA,KAAT,EAAgBC,OAAO,EAAPA,OAAhB,EAA5B,EAAjB,C;;AAEA,IAAMC,eAAe,GAAG,SAAlBA,eAAkB,CAACC,IAAD,EAAOC,IAAP,4BAAsBD,IAAtB,IAA4BC,IAAI,EAAJA,IAA5B,KAAxB,C;;AAEA,IAAMC,YAAY,GAAG,SAAfA,YAAe,CAAAC,OAAO,UAAI,UAAAC,cAAc;AACnD,oBAAED,OAAF,EAAW,CAAC,aAAIE,SAAS,CAACD,cAAD,CAAb,CAAD,EAAiC,gBAAOE,kBAAP,CAAjC,CAAX,CADmD,GAAlB,EAA5B,C;;AAGA,IAAMD,SAAS,GAAG,SAAZA,SAAY,CAAAE,cAAc,UAAI,UAAAP,IAAI;AAC7CA,MAAAA,IAAI,CAACF,OAAL,CAAaS,cAAb,IAA+B,IAA/B,GAAsCR,eAAe,CAACC,IAAD,EAAOO,cAAP,CADR,GAAR,EAAhC,C","sourcesContent":["import { filter, map } from \"lodash/fp\"\r\nimport { $, isSomething } from \"./index\"\r\n\r\nexport const stringNotEmpty = s => isSomething(s) && s.trim().length > 0\r\n\r\nexport const makerule = (field, error, isValid) => ({ field, error, isValid })\r\n\r\nexport const validationError = (rule, item) => ({ ...rule, item })\r\n\r\nexport const applyRuleSet = ruleSet => itemToValidate =>\r\n $(ruleSet, [map(applyRule(itemToValidate)), filter(isSomething)])\r\n\r\nexport const applyRule = itemTovalidate => rule =>\r\n rule.isValid(itemTovalidate) ? null : validationError(rule, itemTovalidate)\r\n"],"file":"validationCommon.js"} \ No newline at end of file diff --git a/packages/common/lib/index.js.map b/packages/common/lib/index.js.map index 5b622752d3..b85820dd03 100644 --- a/packages/common/lib/index.js.map +++ b/packages/common/lib/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.js"],"names":[],"mappings":"kpBAAA;AACA;AACA;AACA","sourcesContent":["export { validateRecord } from \"./records/validateRecord\";\nexport { events } from \"./common/events\";\nexport { safeParseField } from \"./schema/types\";\nexport { default as schemaValidator } from \"./schemaValidation\";"],"file":"index.js"} \ No newline at end of file +{"version":3,"sources":["../src/index.js"],"names":[],"mappings":"kpBAAA;AACA;AACA;AACA","sourcesContent":["export { validateRecord } from \"./records/validateRecord\";\r\nexport { events } from \"./common/events\";\r\nexport { safeParseField } from \"./schema/types\";\r\nexport { default as schemaValidator } from \"./schemaValidation\";"],"file":"index.js"} \ No newline at end of file diff --git a/packages/common/lib/records/getNewRecord.js b/packages/common/lib/records/getNewRecord.js index b0634d6264..13f9df10f0 100644 --- a/packages/common/lib/records/getNewRecord.js +++ b/packages/common/lib/records/getNewRecord.js @@ -1,17 +1,16 @@ "use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.getNewRecord = void 0;var _shortid = require("shortid"); -var _types = require("../schema/types");function _createForOfIteratorHelper(o) {if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {var i = 0;var F = function F() {};return { s: F, n: function n() {if (i >= o.length) return { done: true };return { done: false, value: o[i++] };}, e: function e(_e) {throw _e;}, f: F };}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var it,normalCompletion = true,didErr = false,err;return { s: function s() {it = o[Symbol.iterator]();}, n: function n() {var step = it.next();normalCompletion = step.done;return step;}, e: function e(_e2) {didErr = true;err = _e2;}, f: function f() {try {if (!normalCompletion && it["return"] != null) it["return"]();} finally {if (didErr) throw err;}} };}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(n);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;} var getNewRecord = function getNewRecord(schema, modelName) { var model = schema.findModel(modelName); var record = { _id: (0, _shortid.generate)(), - _modelId: model.id };var _iterator = _createForOfIteratorHelper( + modelId: model._id }; - model.fields),_step;try {for (_iterator.s(); !(_step = _iterator.n()).done;) {var field = _step.value; - record[field.name] = (0, _types.getNewFieldValue)(field); - }} catch (err) {_iterator.e(err);} finally {_iterator.f();} + for (var field in model.schema.properties) { + record[field] = field["default"]; + } return record; };exports.getNewRecord = getNewRecord; diff --git a/packages/common/lib/records/getNewRecord.js.map b/packages/common/lib/records/getNewRecord.js.map index 5c9a88d2a6..c693ff3589 100644 --- a/packages/common/lib/records/getNewRecord.js.map +++ b/packages/common/lib/records/getNewRecord.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/records/getNewRecord.js"],"names":["getNewRecord","schema","modelName","model","findModel","record","_id","_modelId","id","fields","field","name"],"mappings":"yGAAA;AACA,wC;;AAEO,IAAMA,YAAY,GAAG,SAAfA,YAAe,CAACC,MAAD,EAASC,SAAT,EAAuB;AACjD,MAAMC,KAAK,GAAGF,MAAM,CAACG,SAAP,CAAiBF,SAAjB,CAAd;;AAEA,MAAMG,MAAM,GAAG;AACbC,IAAAA,GAAG,EAAE,wBADQ;AAEbC,IAAAA,QAAQ,EAAEJ,KAAK,CAACK,EAFH,EAAf,CAHiD;;;AAQ/BL,EAAAA,KAAK,CAACM,MARyB,aAQjD,oDAAgC,KAAvBC,KAAuB;AAC9BL,MAAAA,MAAM,CAACK,KAAK,CAACC,IAAP,CAAN,GAAqB,6BAAiBD,KAAjB,CAArB;AACD,KAVgD;;AAYjD,SAAOL,MAAP;AACD,CAbM,C","sourcesContent":["import { generate } from \"shortid\"\nimport { getNewFieldValue } from \"../schema/types\"\n\nexport const getNewRecord = (schema, modelName) => {\n const model = schema.findModel(modelName)\n\n const record = {\n _id: generate(),\n _modelId: model.id,\n }\n\n for (let field of model.fields) {\n record[field.name] = getNewFieldValue(field)\n }\n\n return record\n}\n"],"file":"getNewRecord.js"} \ No newline at end of file +{"version":3,"sources":["../../src/records/getNewRecord.js"],"names":["getNewRecord","schema","modelName","model","findModel","record","_id","modelId","field","properties"],"mappings":"yGAAA;;AAEO,IAAMA,YAAY,GAAG,SAAfA,YAAe,CAACC,MAAD,EAASC,SAAT,EAAuB;AACjD,MAAMC,KAAK,GAAGF,MAAM,CAACG,SAAP,CAAiBF,SAAjB,CAAd;;AAEA,MAAMG,MAAM,GAAG;AACbC,IAAAA,GAAG,EAAE,wBADQ;AAEbC,IAAAA,OAAO,EAAEJ,KAAK,CAACG,GAFF,EAAf;;;AAKA,OAAK,IAAIE,KAAT,IAAkBL,KAAK,CAACF,MAAN,CAAaQ,UAA/B,EAA2C;AACzCJ,IAAAA,MAAM,CAACG,KAAD,CAAN,GAAgBA,KAAK,WAArB;AACD;;AAED,SAAOH,MAAP;AACD,CAbM,C","sourcesContent":["import { generate } from \"shortid\"\r\n\r\nexport const getNewRecord = (schema, modelName) => {\r\n const model = schema.findModel(modelName)\r\n\r\n const record = {\r\n _id: generate(),\r\n modelId: model._id,\r\n }\r\n\r\n for (let field in model.schema.properties) {\r\n record[field] = field.default\r\n }\r\n\r\n return record\r\n}\r\n"],"file":"getNewRecord.js"} \ No newline at end of file diff --git a/packages/common/lib/records/recordValidationRules.js.map b/packages/common/lib/records/recordValidationRules.js.map index 789f133bc6..b2436d7b82 100644 --- a/packages/common/lib/records/recordValidationRules.js.map +++ b/packages/common/lib/records/recordValidationRules.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/records/recordValidationRules.js"],"names":["getNewRecordValidationRule","invalidField","messageWhenInvalid","expressionWhenValid","commonRecordValidationRules","fieldNotEmpty","fieldName","fieldBetween","min","max","toString","fieldGreaterThan"],"mappings":"6JAAO,IAAMA,0BAA0B,GAAG,SAA7BA,0BAA6B;AACxCC,YADwC;AAExCC,kBAFwC;AAGxCC,mBAHwC;AAIpC;AACJF,MAAAA,YAAY,EAAZA,YADI;AAEJC,MAAAA,kBAAkB,EAAlBA,kBAFI;AAGJC,MAAAA,mBAAmB,EAAnBA,mBAHI,EAJoC,GAAnC,C;;;AAUA,IAAMC,2BAA2B,GAAG;AACzCC,EAAAA,aAAa,EAAE,uBAAAC,SAAS;AACtBN,MAAAA,0BAA0B;AACxBM,MAAAA,SADwB;AAErBA,MAAAA,SAFqB;AAGbA,MAAAA,SAHa,2BAGaA,SAHb,mBADJ,GADiB;;;AAQzCC,EAAAA,YAAY,EAAE,sBAACD,SAAD,EAAYE,GAAZ,EAAiBC,GAAjB;AACZT,MAAAA,0BAA0B;AACxBM,MAAAA,SADwB;AAErBA,MAAAA,SAFqB,8BAEQE,GAAG,CAACE,QAAJ,EAFR,kBAE8BD,GAAG,CAACC,QAAJ,EAF9B;AAGbJ,MAAAA,SAHa,mBAGKE,GAHL,0BAGwBF,SAHxB,mBAG0CG,GAH1C,OADd,GAR2B;;;AAezCE,EAAAA,gBAAgB,EAAE,0BAACL,SAAD,EAAYE,GAAZ,EAAiBC,GAAjB;AAChBT,MAAAA,0BAA0B;AACxBM,MAAAA,SADwB;AAErBA,MAAAA,SAFqB,mCAEaE,GAAG,CAACE,QAAJ,EAFb,kBAEmCD,GAAG,CAACC,QAAJ,EAFnC;AAGbJ,MAAAA,SAHa,mBAGKE,GAHL,QADV,GAfuB,EAApC,C","sourcesContent":["export const getNewRecordValidationRule = (\n invalidField,\n messageWhenInvalid,\n expressionWhenValid\n) => ({\n invalidField,\n messageWhenInvalid,\n expressionWhenValid,\n})\n\nexport const commonRecordValidationRules = {\n fieldNotEmpty: fieldName =>\n getNewRecordValidationRule(\n fieldName,\n `${fieldName} is empty`,\n `record['${fieldName}'] && record['${fieldName}'].length > 0`\n ),\n\n fieldBetween: (fieldName, min, max) =>\n getNewRecordValidationRule(\n fieldName,\n `${fieldName} must be between ${min.toString()} and ${max.toString()}`,\n `record['${fieldName}'] >= ${min} && record['${fieldName}'] <= ${max} `\n ),\n\n fieldGreaterThan: (fieldName, min, max) =>\n getNewRecordValidationRule(\n fieldName,\n `${fieldName} must be greater than ${min.toString()} and ${max.toString()}`,\n `record['${fieldName}'] >= ${min} `\n ),\n}\n"],"file":"recordValidationRules.js"} \ No newline at end of file +{"version":3,"sources":["../../src/records/recordValidationRules.js"],"names":["getNewRecordValidationRule","invalidField","messageWhenInvalid","expressionWhenValid","commonRecordValidationRules","fieldNotEmpty","fieldName","fieldBetween","min","max","toString","fieldGreaterThan"],"mappings":"6JAAO,IAAMA,0BAA0B,GAAG,SAA7BA,0BAA6B;AACxCC,YADwC;AAExCC,kBAFwC;AAGxCC,mBAHwC;AAIpC;AACJF,MAAAA,YAAY,EAAZA,YADI;AAEJC,MAAAA,kBAAkB,EAAlBA,kBAFI;AAGJC,MAAAA,mBAAmB,EAAnBA,mBAHI,EAJoC,GAAnC,C;;;AAUA,IAAMC,2BAA2B,GAAG;AACzCC,EAAAA,aAAa,EAAE,uBAAAC,SAAS;AACtBN,MAAAA,0BAA0B;AACxBM,MAAAA,SADwB;AAErBA,MAAAA,SAFqB;AAGbA,MAAAA,SAHa,2BAGaA,SAHb,mBADJ,GADiB;;;AAQzCC,EAAAA,YAAY,EAAE,sBAACD,SAAD,EAAYE,GAAZ,EAAiBC,GAAjB;AACZT,MAAAA,0BAA0B;AACxBM,MAAAA,SADwB;AAErBA,MAAAA,SAFqB,8BAEQE,GAAG,CAACE,QAAJ,EAFR,kBAE8BD,GAAG,CAACC,QAAJ,EAF9B;AAGbJ,MAAAA,SAHa,mBAGKE,GAHL,0BAGwBF,SAHxB,mBAG0CG,GAH1C,OADd,GAR2B;;;AAezCE,EAAAA,gBAAgB,EAAE,0BAACL,SAAD,EAAYE,GAAZ,EAAiBC,GAAjB;AAChBT,MAAAA,0BAA0B;AACxBM,MAAAA,SADwB;AAErBA,MAAAA,SAFqB,mCAEaE,GAAG,CAACE,QAAJ,EAFb,kBAEmCD,GAAG,CAACC,QAAJ,EAFnC;AAGbJ,MAAAA,SAHa,mBAGKE,GAHL,QADV,GAfuB,EAApC,C","sourcesContent":["export const getNewRecordValidationRule = (\r\n invalidField,\r\n messageWhenInvalid,\r\n expressionWhenValid\r\n) => ({\r\n invalidField,\r\n messageWhenInvalid,\r\n expressionWhenValid,\r\n})\r\n\r\nexport const commonRecordValidationRules = {\r\n fieldNotEmpty: fieldName =>\r\n getNewRecordValidationRule(\r\n fieldName,\r\n `${fieldName} is empty`,\r\n `record['${fieldName}'] && record['${fieldName}'].length > 0`\r\n ),\r\n\r\n fieldBetween: (fieldName, min, max) =>\r\n getNewRecordValidationRule(\r\n fieldName,\r\n `${fieldName} must be between ${min.toString()} and ${max.toString()}`,\r\n `record['${fieldName}'] >= ${min} && record['${fieldName}'] <= ${max} `\r\n ),\r\n\r\n fieldGreaterThan: (fieldName, min, max) =>\r\n getNewRecordValidationRule(\r\n fieldName,\r\n `${fieldName} must be greater than ${min.toString()} and ${max.toString()}`,\r\n `record['${fieldName}'] >= ${min} `\r\n ),\r\n}\r\n"],"file":"recordValidationRules.js"} \ No newline at end of file diff --git a/packages/common/lib/records/validateRecord.js.map b/packages/common/lib/records/validateRecord.js.map index 450ecedab3..84a6151205 100644 --- a/packages/common/lib/records/validateRecord.js.map +++ b/packages/common/lib/records/validateRecord.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/records/validateRecord.js"],"names":["fieldParseError","fieldName","value","fields","message","validateAllFieldParse","record","model","f","name","parseResult","errors","success","push","validateAllTypeConstraints","field","isNonEmptyString","m","e","runRecordValidationRules","runValidationRule","rule","isValid","expressionWhenValid","expressionContext","valid","invalidFields","messageWhenInvalid","validationRules","flatten","r","validateRecord","schema","findModel","_modelId","fieldParseFails","recordValidationRuleFails","typeContraintFails"],"mappings":"2GAAA;AACA;AACA;;;;AAIA,4C;;AAEA,IAAMA,eAAe,GAAG,SAAlBA,eAAkB,CAACC,SAAD,EAAYC,KAAZ,UAAuB;AAC7CC,IAAAA,MAAM,EAAE,CAACF,SAAD,CADqC;AAE7CG,IAAAA,OAAO,kCAA2BH,SAA3B,cAAwCC,KAAxC,CAFsC,EAAvB,EAAxB;;;AAKA,IAAMG,qBAAqB,GAAG,SAAxBA,qBAAwB,CAACC,MAAD,EAASC,KAAT;AAC5B,mBAAEA,KAAK,CAACJ,MAAR,EAAgB;AACd,iBAAI,UAAAK,CAAC,UAAK,EAAEC,IAAI,EAAED,CAAC,CAACC,IAAV,EAAgBC,WAAW,EAAE,+BAAmBF,CAAnB,EAAsBF,MAAtB,CAA7B,EAAL,EAAL,CADc;AAEd,oBAAO,UAACK,MAAD,EAASH,CAAT,EAAe;AACpB,UAAIA,CAAC,CAACE,WAAF,CAAcE,OAAlB,EAA2B,OAAOD,MAAP;AAC3BA,MAAAA,MAAM,CAACE,IAAP,CAAYb,eAAe,CAACQ,CAAC,CAACC,IAAH,EAASD,CAAC,CAACE,WAAF,CAAcR,KAAvB,CAA3B;AACA,aAAOS,MAAP;AACD,KAJD,EAIG,EAJH,CAFc,CAAhB,CAD4B,GAA9B;;;AAUA,IAAMG,0BAA0B,GAAG,SAA7BA,0BAA6B,CAACR,MAAD,EAASC,KAAT,EAAmB;AACpD,MAAMI,MAAM,GAAG,EAAf,CADoD;AAEhCJ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AAzB,CAAP;;AAMD,CAnBD;;AAqBO,IAAM2B,cAAc,GAAG,SAAjBA,cAAiB,CAACC,MAAD,EAAS1B,MAAT,EAAoB;AAChD,MAAMC,KAAK,GAAGyB,MAAM,CAACC,SAAP,CAAiB3B,MAAM,CAAC4B,QAAxB,CAAd;AACA,MAAMC,eAAe,GAAG9B,qBAAqB,CAACC,MAAD,EAASC,KAAT,CAA7C;;AAEA;AACA,MAAI,CAAC,iBAAQ4B,eAAR,CAAL,EAA+B;AAC7B,WAAO,EAAEb,OAAO,EAAE,KAAX,EAAkBX,MAAM,EAAEwB,eAA1B,EAAP;AACD;;AAED,MAAMC,yBAAyB,GAAGjB,wBAAwB,CAACb,MAAD,EAASC,KAAT,CAA1D;AACA,MAAM8B,kBAAkB,GAAGvB,0BAA0B,CAACR,MAAD,EAASC,KAAT,CAArD;;AAEA;AACE,mBAAQ4B,eAAR;AACA,mBAAQC,yBAAR,CADA;AAEA,mBAAQC,kBAAR,CAHF;AAIE;AACA,WAAO,EAAEf,OAAO,EAAE,IAAX,EAAiBX,MAAM,EAAE,EAAzB,EAAP;AACD;;AAED,SAAO;AACLW,IAAAA,OAAO,EAAE,KADJ;AAELX,IAAAA,MAAM,EAAE;AACNwB,IAAAA,eADM;AAENE,IAAAA,kBAFM;AAGND,IAAAA,yBAHM,CAFH,EAAP;;;AAQD,CA5BM,C","sourcesContent":["import { map, reduce, filter, isEmpty, flatten, each, union } from \"lodash/fp\";\nimport { compileCode } from \"../common/compileCode\";\nimport {\n validateFieldParse,\n validateTypeConstraints,\n} from \"../schema/types/index.js\"\nimport { $, isNonEmptyString } from \"../common/index.js\"\n\nconst fieldParseError = (fieldName, value) => ({\n fields: [fieldName],\n message: `Could not parse field ${fieldName}:${value}`,\n})\n\nconst validateAllFieldParse = (record, model) =>\n $(model.fields, [\n map(f => ({ name: f.name, parseResult: validateFieldParse(f, record) })),\n reduce((errors, f) => {\n if (f.parseResult.success) return errors\n errors.push(fieldParseError(f.name, f.parseResult.value))\n return errors\n }, []),\n ])\n\nconst validateAllTypeConstraints = (record, model) => {\n const errors = []\n for (const field of model.fields) {\n $(validateTypeConstraints(field, record), [\n filter(isNonEmptyString),\n map(m => ({ message: m, fields: [field.name] })),\n each(e => errors.push(e)),\n ])\n }\n return errors\n}\n\nconst runRecordValidationRules = (record, model) => {\n const runValidationRule = rule => {\n const isValid = compileCode(rule.expressionWhenValid)\n const expressionContext = { record }\n return isValid(expressionContext)\n ? { valid: true }\n : {\n valid: false,\n fields: rule.invalidFields,\n message: rule.messageWhenInvalid,\n }\n }\n\n return $(model.validationRules, [\n map(runValidationRule),\n flatten,\n filter(r => r.valid === false),\n map(r => ({ fields: r.fields, message: r.message })),\n ])\n}\n\nexport const validateRecord = (schema, record) => {\n const model = schema.findModel(record._modelId)\n const fieldParseFails = validateAllFieldParse(record, model)\n\n // non parsing would cause further issues - exit here\n if (!isEmpty(fieldParseFails)) {\n return { isValid: false, errors: fieldParseFails }\n }\n\n const recordValidationRuleFails = runRecordValidationRules(record, model)\n const typeContraintFails = validateAllTypeConstraints(record, model)\n\n if (\n isEmpty(fieldParseFails) &&\n isEmpty(recordValidationRuleFails) &&\n isEmpty(typeContraintFails)\n ) {\n return { isValid: true, errors: [] }\n }\n\n return {\n isValid: false,\n errors: union(\n fieldParseFails,\n typeContraintFails,\n recordValidationRuleFails\n ),\n }\n}\n"],"file":"validateRecord.js"} \ No newline at end of file +{"version":3,"sources":["../../src/records/validateRecord.js"],"names":["fieldParseError","fieldName","value","fields","message","validateAllFieldParse","record","model","f","name","parseResult","errors","success","push","validateAllTypeConstraints","field","isNonEmptyString","m","e","runRecordValidationRules","runValidationRule","rule","isValid","expressionWhenValid","expressionContext","valid","invalidFields","messageWhenInvalid","validationRules","flatten","r","validateRecord","schema","findModel","_modelId","fieldParseFails","recordValidationRuleFails","typeContraintFails"],"mappings":"2GAAA;AACA;AACA;;;;AAIA,4C;;AAEA,IAAMA,eAAe,GAAG,SAAlBA,eAAkB,CAACC,SAAD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AAGjB,wBAAwB,CAACb,MAAD,EAASC,KAAT,CAA1D;AACA,MAAM8B,kBAAkB,GAAGvB,0BAA0B,CAACR,MAAD,EAASC,KAAT,CAArD;;AAEA;AACE,mBAAQ4B,eAAR;AACA,mBAAQC,yBAAR,CADA;AAEA,mBAAQC,kBAAR,CAHF;AAIE;AACA,WAAO,EAAEf,OAAO,EAAE,IAAX,EAAiBX,MAAM,EAAE,EAAzB,EAAP;AACD;;AAED,SAAO;AACLW,IAAAA,OAAO,EAAE,KADJ;AAELX,IAAAA,MAAM,EAAE;AACNwB,IAAAA,eADM;AAENE,IAAAA,kBAFM;AAGND,IAAAA,yBAHM,CAFH,EAAP;;;AAQD,CA5BM,C","sourcesContent":["import { map, reduce, filter, isEmpty, flatten, each, union } from \"lodash/fp\";\r\nimport { compileCode } from \"../common/compileCode\";\r\nimport {\r\n validateFieldParse,\r\n validateTypeConstraints,\r\n} from \"../schema/types/index.js\"\r\nimport { $, isNonEmptyString } from \"../common/index.js\"\r\n\r\nconst fieldParseError = (fieldName, value) => ({\r\n fields: [fieldName],\r\n message: `Could not parse field ${fieldName}:${value}`,\r\n})\r\n\r\nconst validateAllFieldParse = (record, model) =>\r\n $(model.fields, [\r\n map(f => ({ name: f.name, parseResult: validateFieldParse(f, record) })),\r\n reduce((errors, f) => {\r\n if (f.parseResult.success) return errors\r\n errors.push(fieldParseError(f.name, f.parseResult.value))\r\n return errors\r\n }, []),\r\n ])\r\n\r\nconst validateAllTypeConstraints = (record, model) => {\r\n const errors = []\r\n for (const field of model.fields) {\r\n $(validateTypeConstraints(field, record), [\r\n filter(isNonEmptyString),\r\n map(m => ({ message: m, fields: [field.name] })),\r\n each(e => errors.push(e)),\r\n ])\r\n }\r\n return errors\r\n}\r\n\r\nconst runRecordValidationRules = (record, model) => {\r\n const runValidationRule = rule => {\r\n const isValid = compileCode(rule.expressionWhenValid)\r\n const expressionContext = { record }\r\n return isValid(expressionContext)\r\n ? { valid: true }\r\n : {\r\n valid: false,\r\n fields: rule.invalidFields,\r\n message: rule.messageWhenInvalid,\r\n }\r\n }\r\n\r\n return $(model.validationRules, [\r\n map(runValidationRule),\r\n flatten,\r\n filter(r => r.valid === false),\r\n map(r => ({ fields: r.fields, message: r.message })),\r\n ])\r\n}\r\n\r\nexport const validateRecord = (schema, record) => {\r\n const model = schema.findModel(record._modelId)\r\n const fieldParseFails = validateAllFieldParse(record, model)\r\n\r\n // non parsing would cause further issues - exit here\r\n if (!isEmpty(fieldParseFails)) {\r\n return { isValid: false, errors: fieldParseFails }\r\n }\r\n\r\n const recordValidationRuleFails = runRecordValidationRules(record, model)\r\n const typeContraintFails = validateAllTypeConstraints(record, model)\r\n\r\n if (\r\n isEmpty(fieldParseFails) &&\r\n isEmpty(recordValidationRuleFails) &&\r\n isEmpty(typeContraintFails)\r\n ) {\r\n return { isValid: true, errors: [] }\r\n }\r\n\r\n return {\r\n isValid: false,\r\n errors: union(\r\n fieldParseFails,\r\n typeContraintFails,\r\n recordValidationRuleFails\r\n ),\r\n }\r\n}\r\n"],"file":"validateRecord.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/createActions.js.map b/packages/common/lib/schema/createActions.js.map index 2362409748..2c0777b2d0 100644 --- a/packages/common/lib/schema/createActions.js.map +++ b/packages/common/lib/schema/createActions.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/schema/createActions.js"],"names":["createTrigger","actionName","eventName","optionsCreator","condition","createAction","name","behaviourSource","behaviourName","initialOptions"],"mappings":"iIAAO,IAAMA,aAAa,GAAG,SAAhBA,aAAgB,WAAO;AAClCC,IAAAA,UAAU,EAAE,EADsB;AAElCC,IAAAA,SAAS,EAAE,EAFuB;AAGlC;AACA;AACA;AACAC,IAAAA,cAAc,EAAE,EANkB;AAOlC;AACA;AACAC,IAAAA,SAAS,EAAE,EATuB,EAAP,EAAtB,C;;;AAYA,IAAMC,YAAY,GAAG,SAAfA,YAAe,WAAO;AACjCC,IAAAA,IAAI,EAAE,EAD2B;AAEjCC,IAAAA,eAAe,EAAE,EAFgB;AAGjC;AACAC,IAAAA,aAAa,EAAE,EAJkB;AAKjC;AACA;AACA;AACAC,IAAAA,cAAc,EAAE,EARiB,EAAP,EAArB,C","sourcesContent":["export const createTrigger = () => ({\n actionName: \"\",\n eventName: \"\",\n // function, has access to event context,\n // returns object that is used as parameter to action\n // only used if triggered by event\n optionsCreator: \"\",\n // action runs if true,\n // has access to event context\n condition: \"\",\n})\n\nexport const createAction = () => ({\n name: \"\",\n behaviourSource: \"\",\n // name of function in actionSource\n behaviourName: \"\",\n // parameter passed into behaviour.\n // any other parms passed at runtime e.g.\n // by trigger, or manually, will be merged into this\n initialOptions: {},\n})\n"],"file":"createActions.js"} \ No newline at end of file +{"version":3,"sources":["../../src/schema/createActions.js"],"names":["createTrigger","actionName","eventName","optionsCreator","condition","createAction","name","behaviourSource","behaviourName","initialOptions"],"mappings":"iIAAO,IAAMA,aAAa,GAAG,SAAhBA,aAAgB,WAAO;AAClCC,IAAAA,UAAU,EAAE,EADsB;AAElCC,IAAAA,SAAS,EAAE,EAFuB;AAGlC;AACA;AACA;AACAC,IAAAA,cAAc,EAAE,EANkB;AAOlC;AACA;AACAC,IAAAA,SAAS,EAAE,EATuB,EAAP,EAAtB,C;;;AAYA,IAAMC,YAAY,GAAG,SAAfA,YAAe,WAAO;AACjCC,IAAAA,IAAI,EAAE,EAD2B;AAEjCC,IAAAA,eAAe,EAAE,EAFgB;AAGjC;AACAC,IAAAA,aAAa,EAAE,EAJkB;AAKjC;AACA;AACA;AACAC,IAAAA,cAAc,EAAE,EARiB,EAAP,EAArB,C","sourcesContent":["export const createTrigger = () => ({\r\n actionName: \"\",\r\n eventName: \"\",\r\n // function, has access to event context,\r\n // returns object that is used as parameter to action\r\n // only used if triggered by event\r\n optionsCreator: \"\",\r\n // action runs if true,\r\n // has access to event context\r\n condition: \"\",\r\n})\r\n\r\nexport const createAction = () => ({\r\n name: \"\",\r\n behaviourSource: \"\",\r\n // name of function in actionSource\r\n behaviourName: \"\",\r\n // parameter passed into behaviour.\r\n // any other parms passed at runtime e.g.\r\n // by trigger, or manually, will be merged into this\r\n initialOptions: {},\r\n})\r\n"],"file":"createActions.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/fields.js.map b/packages/common/lib/schema/fields.js.map index db27a134e4..968b44c38a 100644 --- a/packages/common/lib/schema/fields.js.map +++ b/packages/common/lib/schema/fields.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/schema/fields.js"],"names":["fieldErrors","AddFieldValidationFailed","allowedTypes","all","getNewField","type","id","name","typeOptions","label","getInitialValue","getUndefinedValue","fieldRules","allFields","f","t","typeOptionsRules","field","def","optName","optionDefinitions","keys","o","isValid","requirementDescription","validateField","everySingleField","validateAllFields","recordNode","fields","flatten","addField","recordTemplate","validationMessages","length","errors","m","error","BadRequestError","join","push"],"mappings":"uZAAA;AACA;;;;;;;AAOA;AACA;AACA;AACA;;AAEO,IAAMA,WAAW,GAAG;AACzBC,EAAAA,wBAAwB,EAAE,wBADD,EAApB,C;;;AAIA,IAAMC,YAAY,GAAG,SAAfA,YAAe,WAAM,cAAKC,UAAL,CAAN,EAArB,C;;AAEA,IAAMC,WAAW,GAAG,SAAdA,WAAc,CAAAC,IAAI,UAAK;AAClCC,IAAAA,EAAE,EAAE,wBAD8B;AAElCC,IAAAA,IAAI,EAAE,EAF4B,EAExB;AACVF,IAAAA,IAAI,EAAJA,IAHkC;AAIlCG,IAAAA,WAAW,EAAE,8BAAkBH,IAAlB,CAJqB;AAKlCI,IAAAA,KAAK,EAAE,EAL2B,EAKvB;AACXC,IAAAA,eAAe,EAAE,SANiB,EAMN;AAC5BC,IAAAA,iBAAiB,EAAE,SAPe,CAOJ;AAPI,GAAL,EAAxB,C;;AAUP,IAAMC,UAAU,GAAG,SAAbA,UAAa,CAAAC,SAAS,UAAI;AAC9B,kCAAS,MAAT,EAAiB,uBAAjB,EAA0C,UAAAC,CAAC,UAAI,8BAAiBA,CAAC,CAACP,IAAnB,CAAJ,EAA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;AAGA,MAAIgB,kBAAkB,CAACC,MAAnB,GAA4B,CAAhC,EAAmC;AACjC,QAAMC,MAAM,GAAG,aAAI,UAAAC,CAAC,UAAIA,CAAC,CAACC,KAAN,EAAL,EAAkBJ,kBAAlB,CAAf;AACA,UAAM,IAAIK,uBAAJ;AACDtC,IAAAA,WAAW,CAACC,wBADX,cACuCkC,MAAM,CAACI,IAAP,CAAY,IAAZ,CADvC,EAAN;;AAGD;AACDP,EAAAA,cAAc,CAACH,MAAf,CAAsBW,IAAtB,CAA2BvB,KAA3B;AACD,CAdM,C","sourcesContent":["import { some, map, filter, keys, includes, countBy, flatten } from \"lodash/fp\"\nimport {\n isSomething,\n $,\n isNonEmptyString,\n isNothingOrEmpty,\n isNothing,\n} from \"../common\"\nimport { all, getDefaultOptions } from \"./types/index.js\"\nimport { applyRuleSet, makerule } from \"../common/validationCommon\"\nimport { BadRequestError } from \"../common/errors\"\nimport { generate } from \"shortid\"\n\nexport const fieldErrors = {\n AddFieldValidationFailed: \"Add field validation: \",\n}\n\nexport const allowedTypes = () => keys(all)\n\nexport const getNewField = type => ({\n id: generate(),\n name: \"\", // how field is referenced internally\n type,\n typeOptions: getDefaultOptions(type),\n label: \"\", // how field is displayed\n getInitialValue: \"default\", // function that gets value when initially created\n getUndefinedValue: \"default\", // function that gets value when field undefined on record\n})\n\nconst fieldRules = allFields => [\n makerule(\"name\", \"field name is not set\", f => isNonEmptyString(f.name)),\n makerule(\"type\", \"field type is not set\", f => isNonEmptyString(f.type)),\n makerule(\"label\", \"field label is not set\", f => isNonEmptyString(f.label)),\n makerule(\"getInitialValue\", \"getInitialValue function is not set\", f =>\n isNonEmptyString(f.getInitialValue)\n ),\n makerule(\"getUndefinedValue\", \"getUndefinedValue function is not set\", f =>\n isNonEmptyString(f.getUndefinedValue)\n ),\n makerule(\n \"name\",\n \"field name is duplicated\",\n f => isNothingOrEmpty(f.name) || countBy(\"name\")(allFields)[f.name] === 1\n ),\n makerule(\n \"type\",\n \"type is unknown\",\n f => isNothingOrEmpty(f.type) || some(t => f.type === t)(allowedTypes())\n ),\n]\n\nconst typeOptionsRules = field => {\n const type = all[field.type]\n if (isNothing(type)) return []\n\n const def = optName => type.optionDefinitions[optName]\n\n return $(field.typeOptions, [\n keys,\n filter(o => isSomething(def(o)) && isSomething(def(o).isValid)),\n map(o =>\n makerule(`typeOptions.${o}`, `${def(o).requirementDescription}`, field =>\n def(o).isValid(field.typeOptions[o])\n )\n ),\n ])\n}\n\nexport const validateField = allFields => field => {\n const everySingleField = includes(field)(allFields)\n ? allFields\n : [...allFields, field]\n return applyRuleSet([\n ...fieldRules(everySingleField),\n ...typeOptionsRules(field),\n ])(field)\n}\n\nexport const validateAllFields = recordNode =>\n $(recordNode.fields, [map(validateField(recordNode.fields)), flatten])\n\nexport const addField = (recordTemplate, field) => {\n if (isNothingOrEmpty(field.label)) {\n field.label = field.name\n }\n const validationMessages = validateField([...recordTemplate.fields, field])(\n field\n )\n if (validationMessages.length > 0) {\n const errors = map(m => m.error)(validationMessages)\n throw new BadRequestError(\n `${fieldErrors.AddFieldValidationFailed} ${errors.join(\", \")}`\n )\n }\n recordTemplate.fields.push(field)\n}\n"],"file":"fields.js"} \ No newline at end of file +{"version":3,"sources":["../../src/schema/fields.js"],"names":["fieldErrors","AddFieldValidationFailed","allowedTypes","all","getNewField","type","id","name","typeOptions","label","getInitialValue","getUndefinedValue","fieldRules","allFields","f","t","typeOptionsRules","field","def","optName","optionDefinitions","keys","o","isValid","requirementDescription","validateField","everySingleField","validateAllFields","recordNode","fields","flatten","addField","recordTemplate","validationMessages","length","errors","m","error","BadRequestError","join","push"],"mappings":"uZAAA;AACA;;;;;;;AAOA;AACA;AACA;AACA;;AAEO,IAAMA,WAAW,GAAG;AACzBC,EAAAA,wBAAwB,EAAE,wBADD,EAApB,C;;;AAIA,IAAMC,YAAY,GAAG,SAAfA,YAAe,WAAM,cAAKC,UAAL,CAAN,EAArB,C;;AAEA,IAAMC,WAAW,GAAG,SAAdA,W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MU,iBAAiB,GAAG,SAApBA,iBAAoB,CAAAC,UAAU;AACzC,mBAAEA,UAAU,CAACC,MAAb,EAAqB,CAAC,aAAIJ,aAAa,CAACG,UAAU,CAACC,MAAZ,CAAjB,CAAD,EAAwCC,WAAxC,CAArB,CADyC,GAApC,C;;AAGA,IAAMC,QAAQ,GAAG,SAAXA,QAAW,CAACC,cAAD,EAAiBf,KAAjB,EAA2B;AACjD,MAAI,8BAAiBA,KAAK,CAACR,KAAvB,CAAJ,EAAmC;AACjCQ,IAAAA,KAAK,CAACR,KAAN,GAAcQ,KAAK,CAACV,IAApB;AACD;AACD,MAAM0B,kBAAkB,GAAGR,aAAa,+CAAKO,cAAc,CAACH,MAApB,IAA4BZ,KAA5B,GAAb;AACzBA,EAAAA,KADyB,CAA3B;;AAGA,MAAIgB,kBAAkB,CAACC,MAAnB,GAA4B,CAAhC,EAAmC;AACjC,QAAMC,MAAM,GAAG,aAAI,UAAAC,CAAC,UAAIA,CAAC,CAACC,KAAN,EAAL,EAAkBJ,kBAAlB,CAAf;AACA,UAAM,IAAIK,uBAAJ;AACDtC,IAAAA,WAAW,CAACC,wBADX,cACuCkC,MAAM,CAACI,IAAP,CAAY,IAAZ,CADvC,EAAN;;AAGD;AACDP,EAAAA,cAAc,CAACH,MAAf,CAAsBW,IAAtB,CAA2BvB,KAA3B;AACD,CAdM,C","sourcesContent":["import { some, map, filter, keys, includes, countBy, flatten } from \"lodash/fp\"\r\nimport {\r\n isSomething,\r\n $,\r\n isNonEmptyString,\r\n isNothingOrEmpty,\r\n isNothing,\r\n} from \"../common\"\r\nimport { all, getDefaultOptions } from \"./types/index.js\"\r\nimport { applyRuleSet, makerule } from \"../common/validationCommon\"\r\nimport { BadRequestError } from \"../common/errors\"\r\nimport { generate } from \"shortid\"\r\n\r\nexport const fieldErrors = {\r\n AddFieldValidationFailed: \"Add field validation: \",\r\n}\r\n\r\nexport const allowedTypes = () => keys(all)\r\n\r\nexport const getNewField = type => ({\r\n id: generate(),\r\n name: \"\", // how field is referenced internally\r\n type,\r\n typeOptions: getDefaultOptions(type),\r\n label: \"\", // how field is displayed\r\n getInitialValue: \"default\", // function that gets value when initially created\r\n getUndefinedValue: \"default\", // function that gets value when field undefined on record\r\n})\r\n\r\nconst fieldRules = allFields => [\r\n makerule(\"name\", \"field name is not set\", f => isNonEmptyString(f.name)),\r\n makerule(\"type\", \"field type is not set\", f => isNonEmptyString(f.type)),\r\n makerule(\"label\", \"field label is not set\", f => isNonEmptyString(f.label)),\r\n makerule(\"getInitialValue\", \"getInitialValue function is not set\", f =>\r\n isNonEmptyString(f.getInitialValue)\r\n ),\r\n makerule(\"getUndefinedValue\", \"getUndefinedValue function is not set\", f =>\r\n isNonEmptyString(f.getUndefinedValue)\r\n ),\r\n makerule(\r\n \"name\",\r\n \"field name is duplicated\",\r\n f => isNothingOrEmpty(f.name) || countBy(\"name\")(allFields)[f.name] === 1\r\n ),\r\n makerule(\r\n \"type\",\r\n \"type is unknown\",\r\n f => isNothingOrEmpty(f.type) || some(t => f.type === t)(allowedTypes())\r\n ),\r\n]\r\n\r\nconst typeOptionsRules = field => {\r\n const type = all[field.type]\r\n if (isNothing(type)) return []\r\n\r\n const def = optName => type.optionDefinitions[optName]\r\n\r\n return $(field.typeOptions, [\r\n keys,\r\n filter(o => isSomething(def(o)) && isSomething(def(o).isValid)),\r\n map(o =>\r\n makerule(`typeOptions.${o}`, `${def(o).requirementDescription}`, field =>\r\n def(o).isValid(field.typeOptions[o])\r\n )\r\n ),\r\n ])\r\n}\r\n\r\nexport const validateField = allFields => field => {\r\n const everySingleField = includes(field)(allFields)\r\n ? allFields\r\n : [...allFields, field]\r\n return applyRuleSet([\r\n ...fieldRules(everySingleField),\r\n ...typeOptionsRules(field),\r\n ])(field)\r\n}\r\n\r\nexport const validateAllFields = recordNode =>\r\n $(recordNode.fields, [map(validateField(recordNode.fields)), flatten])\r\n\r\nexport const addField = (recordTemplate, field) => {\r\n if (isNothingOrEmpty(field.label)) {\r\n field.label = field.name\r\n }\r\n const validationMessages = validateField([...recordTemplate.fields, field])(\r\n field\r\n )\r\n if (validationMessages.length > 0) {\r\n const errors = map(m => m.error)(validationMessages)\r\n throw new BadRequestError(\r\n `${fieldErrors.AddFieldValidationFailed} ${errors.join(\", \")}`\r\n )\r\n }\r\n recordTemplate.fields.push(field)\r\n}\r\n"],"file":"fields.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/fullSchema.js.map b/packages/common/lib/schema/fullSchema.js.map index 5eece533a2..2ed48241a5 100644 --- a/packages/common/lib/schema/fullSchema.js.map +++ b/packages/common/lib/schema/fullSchema.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/schema/fullSchema.js"],"names":["fullSchema","models","views","findModel","idOrName","find","m","id","name","toLowerCase","findView","findField","modelIdOrName","fieldName","model","fields","f","viewsForModel","modelId","filter","v"],"mappings":"uGAAO,IAAMA,UAAU,GAAG,SAAbA,UAAa,CAACC,MAAD,EAASC,KAAT,EAAmB;AAC3C,MAAMC,SAAS,GAAG,SAAZA,SAAY,CAAAC,QAAQ;AACxBH,MAAAA,MAAM,CAACI,IAAP;AACE,gBAAAC,CAAC,UAAIA,CAAC,CAACC,EAAF,KAASH,QAAT,IAAqBE,CAAC,CAACE,IAAF,CAAOC,WAAP,OAAyBL,QAAQ,CAACK,WAAT,EAAlD,EADH,CADwB,GAA1B;;;AAKA,MAAMC,QAAQ,GAAG,SAAXA,QAAW,CAAAN,QAAQ;AACvBF,MAAAA,KAAK,CAACG,IAAN;AACE,gBAAAC,CAAC,UAAIA,CAAC,CAACC,EAAF,KAASH,QAAT,IAAqBE,CAAC,CAACE,IAAF,CAAOC,WAAP,OAAyBL,QAAQ,CAACK,WAAT,EAAlD,EADH,CADuB,GAAzB;;;AAKA,MAAME,SAAS,GAAG,SAAZA,SAAY,CAACC,aAAD,EAAgBC,SAAhB,EAA8B;AAC9C,QAAMC,KAAK,GAAGb,MAAM,CAACI,IAAP;AACZ,cAAAC,CAAC;AACCA,QAAAA,CAAC,CAACC,EAAF,KAASK,aAAT;AACAN,QAAAA,CAAC,CAACE,IAAF,CAAOC,WAAP,OAAyBG,aAAa,CAACH,WAAd,EAF1B,GADW,CAAd;;AAKA,WAAOK,KAAK,CAACC,MAAN,CAAaV,IAAb;AACL,cAAAW,CAAC,UAAIA,CAAC,CAACR,IAAF,CAAOC,WAAP,OAAyBI,SAAS,CAACJ,WAAV,EAA7B,EADI,CAAP;;AAGD,GATD;;AAWA,MAAMQ,aAAa,GAAG,SAAhBA,aAAgB,CAAAC,OAAO,UAAIhB,KAAK,CAACiB,MAAN,CAAa,UAAAC,CAAC,UAAIA,CAAC,CAACF,OAAF,KAAcA,OAAlB,EAAd,CAAJ,EAA7B;;AAEA,SAAO;AACLjB,IAAAA,MAAM,EAANA,MADK;AAELC,IAAAA,KAAK,EAALA,KAFK;AAGLC,IAAAA,SAAS,EAATA,SAHK;AAILQ,IAAAA,SAAS,EAATA,SAJK;AAKLD,IAAAA,QAAQ,EAARA,QALK;AAMLO,IAAAA,aAAa,EAAbA,aANK,EAAP;;AAQD,CAhCM,C","sourcesContent":["export const fullSchema = (models, views) => {\n const findModel = idOrName =>\n models.find(\n m => m.id === idOrName || m.name.toLowerCase() === idOrName.toLowerCase()\n )\n\n const findView = idOrName =>\n views.find(\n m => m.id === idOrName || m.name.toLowerCase() === idOrName.toLowerCase()\n )\n\n const findField = (modelIdOrName, fieldName) => {\n const model = models.find(\n m =>\n m.id === modelIdOrName ||\n m.name.toLowerCase() === modelIdOrName.toLowerCase()\n )\n return model.fields.find(\n f => f.name.toLowerCase() === fieldName.toLowerCase()\n )\n }\n\n const viewsForModel = modelId => views.filter(v => v.modelId === modelId)\n\n return {\n models,\n views,\n findModel,\n findField,\n findView,\n viewsForModel,\n }\n}\n"],"file":"fullSchema.js"} \ No newline at end of file +{"version":3,"sources":["../../src/schema/fullSchema.js"],"names":["fullSchema","models","views","findModel","idOrName","find","m","id","name","toLowerCase","findView","findField","modelIdOrName","fieldName","model","fields","f","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EAALA,KAFK;AAGLC,IAAAA,SAAS,EAATA,SAHK;AAILQ,IAAAA,SAAS,EAATA,SAJK;AAKLD,IAAAA,QAAQ,EAARA,QALK;AAMLO,IAAAA,aAAa,EAAbA,aANK,EAAP;;AAQD,CAhCM,C","sourcesContent":["export const fullSchema = (models, views) => {\r\n const findModel = idOrName =>\r\n models.find(\r\n m => m.id === idOrName || m.name.toLowerCase() === idOrName.toLowerCase()\r\n )\r\n\r\n const findView = idOrName =>\r\n views.find(\r\n m => m.id === idOrName || m.name.toLowerCase() === idOrName.toLowerCase()\r\n )\r\n\r\n const findField = (modelIdOrName, fieldName) => {\r\n const model = models.find(\r\n m =>\r\n m.id === modelIdOrName ||\r\n m.name.toLowerCase() === modelIdOrName.toLowerCase()\r\n )\r\n return model.fields.find(\r\n f => f.name.toLowerCase() === fieldName.toLowerCase()\r\n )\r\n }\r\n\r\n const viewsForModel = modelId => views.filter(v => v.modelId === modelId)\r\n\r\n return {\r\n models,\r\n views,\r\n findModel,\r\n findField,\r\n findView,\r\n viewsForModel,\r\n }\r\n}\r\n"],"file":"fullSchema.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/models.js b/packages/common/lib/schema/models.js index 4f39b50c02..5350f416a6 100644 --- a/packages/common/lib/schema/models.js +++ b/packages/common/lib/schema/models.js @@ -1,20 +1,25 @@ "use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.canDeleteModel = exports.newModel = void 0;var _shortid = require("shortid");function _createForOfIteratorHelper(o) {if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {var i = 0;var F = function F() {};return { s: F, n: function n() {if (i >= o.length) return { done: true };return { done: false, value: o[i++] };}, e: function e(_e) {throw _e;}, f: F };}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var it,normalCompletion = true,didErr = false,err;return { s: function s() {it = o[Symbol.iterator]();}, n: function n() {var step = it.next();normalCompletion = step.done;return step;}, e: function e(_e2) {didErr = true;err = _e2;}, f: function f() {try {if (!normalCompletion && it["return"] != null) it["return"]();} finally {if (didErr) throw err;}} };}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(n);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;} var newModel = function newModel() {return { - id: (0, _shortid.generate)(), + _id: (0, _shortid.generate)(), name: "", - fields: [], - validationRules: [], - primaryField: "", - views: [] };}; + type: "model", + key: "name", + schema: { + type: "object", + properties: { + name: { type: "string" } }, + + required: ["name"] } };}; + /** - * - * @param {Array} models - * @param {string} modelId - * @returns {} - */exports.newModel = newModel; + * + * @param {Array} models + * @param {string} modelId + * @returns {} + */exports.newModel = newModel; var canDeleteModel = function canDeleteModel(models, modelId) { var errors = [];var _iterator = _createForOfIteratorHelper( diff --git a/packages/common/lib/schema/models.js.map b/packages/common/lib/schema/models.js.map index 506f0d734f..0ba5da05e8 100644 --- a/packages/common/lib/schema/models.js.map +++ b/packages/common/lib/schema/models.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/schema/models.js"],"names":["newModel","id","name","fields","validationRules","primaryField","views","canDeleteModel","models","modelId","errors","model","links","filter","f","type","typeOptions","link","push","canDelete","length"],"mappings":"8HAAA,kC;;AAEO,IAAMA,QAAQ,GAAG,SAAXA,QAAW,WAAO;AAC7BC,IAAAA,EAAE,EAAE,wBADyB;AAE7BC,IAAAA,IAAI,EAAE,EAFuB;AAG7BC,IAAAA,MAAM,EAAE,EAHqB;AAI7BC,IAAAA,eAAe,EAAE,EAJY;AAK7BC,IAAAA,YAAY,EAAE,EALe;AAM7BC,IAAAA,KAAK,EAAE,EANsB,EAAP,EAAjB;;;AASP;;;;;;AAMO,IAAMC,cAAc,GAAG,SAAjBA,cAAiB,CAACC,MAAD,EAASC,OAAT,EAAqB;AACjD,MAAMC,MAAM,GAAG,EAAf,CADiD;;AAG/BF,EAAAA,MAH+B,aAGjD,oDAA0B,KAAjBG,KAAiB;AACxB,UAAMC,KAAK,GAAGD,KAAK,CAACR,MAAN,CAAaU,MAAb;AACZ,gBAAAC,CAAC,UAAIA,CAAC,CAACC,IAAF,KAAW,MAAX,IAAqBD,CAAC,CAACE,WAAF,CAAcP,OAAd,KAA0BA,OAAnD,EADW,CAAd,CADwB;;;AAKPG,MAAAA,KALO,cAKxB,uDAAwB,KAAfK,IAAe;AACtBP,UAAAA,MAAM,CAACQ,IAAP;AACUP,UAAAA,KAAK,CAACT,IADhB,uDAC+De,IAAI,CAACf,IADpE;;AAGD,SATuB;AAUzB,KAbgD;;AAejD,SAAO;AACLQ,IAAAA,MAAM,EAANA,MADK;AAELS,IAAAA,SAAS,EAAET,MAAM,CAACU,MAAP,GAAgB,CAFtB,EAAP;;AAID,CAnBM,C","sourcesContent":["import { generate } from \"shortid\"\n\nexport const newModel = () => ({\n id: generate(),\n name: \"\",\n fields: [],\n validationRules: [],\n primaryField: \"\",\n views: [],\n})\n\n/**\n *\n * @param {Array} models\n * @param {string} modelId\n * @returns {}\n */\nexport const canDeleteModel = (models, modelId) => {\n const errors = []\n\n for (let model of models) {\n const links = model.fields.filter(\n f => f.type === \"link\" && f.typeOptions.modelId === modelId\n )\n\n for (let link of links) {\n errors.push(\n `The \"${model.name}\" model links to this model, via field \"${link.name}\"`\n )\n }\n }\n\n return {\n errors,\n canDelete: errors.length > 0,\n }\n}\n"],"file":"models.js"} \ No newline at end of file +{"version":3,"sources":["../../src/schema/models.js"],"names":["newModel","_id","name","type","key","schema","properties","required","canDeleteModel","models","modelId","errors","model","links","fields","filter","f","typeOptions","link","push","canDelete","length"],"mappings":"8HAAA,kC;;AAEO,IAAMA,QAAQ,GAAG,SAAXA,QAAW,WAAO;AAC7BC,IAAAA,GAAG,EAAE,wBADwB;AAE7BC,IAAAA,IAAI,EAAE,EAFuB;AAG7BC,IAAAA,IAAI,EAAE,OAHuB;AAI7BC,IAAAA,GAAG,EAAE,MAJwB;AAK7BC,IAAAA,MAAM,EAAE;AACNF,MAAAA,IAAI,EAAE,QADA;AAENG,MAAAA,UAAU,EAAE;AACVJ,QAAAA,IAAI,EAAE,EAAEC,IAAI,EAAE,QAAR,EADI,EAFN;;AAKNI,MAAAA,QAAQ,EAAE,CAAC,MAAD,CALJ,EALqB,EAAP,EAAjB;;;;AAcP;;;;;;AAMO,IAAMC,cAAc,GAAG,SAAjBA,cAAiB,CAACC,MAAD,EAASC,OAAT,EAAqB;AACjD,MAAMC,MAAM,GAAG,EAAf,CADiD;;AAG/BF,EAAAA,MAH+B,aAGjD,oDAA0B,KAAjBG,KAAiB;AACxB,UAAMC,KAAK,GAAGD,KAAK,CAACE,MAAN,CAAaC,MAAb;AACZ,gBAAAC,CAAC,UAAIA,CAAC,CAACb,IAAF,KAAW,MAAX,IAAqBa,CAAC,CAACC,WAAF,CAAcP,OAAd,KAA0BA,OAAnD,EADW,CAAd,CADwB;;;AAKPG,MAAAA,KALO,cAKxB,uDAAwB,KAAfK,IAAe;AACtBP,UAAAA,MAAM,CAACQ,IAAP;AACUP,UAAAA,KAAK,CAACV,IADhB,uDAC+DgB,IAAI,CAAChB,IADpE;;AAGD,SATuB;AAUzB,KAbgD;;AAejD,SAAO;AACLS,IAAAA,MAAM,EAANA,MADK;AAELS,IAAAA,SAAS,EAAET,MAAM,CAACU,MAAP,GAAgB,CAFtB,EAAP;;AAID,CAnBM,C","sourcesContent":["import { generate } from \"shortid\"\r\n\r\nexport const newModel = () => ({\r\n _id: generate(),\r\n name: \"\",\r\n type: \"model\",\r\n key: \"name\",\r\n schema: {\r\n type: \"object\",\r\n properties: {\r\n name: { type: \"string\" },\r\n },\r\n required: [\"name\"],\r\n },\r\n})\r\n\r\n/**\r\n *\r\n * @param {Array} models\r\n * @param {string} modelId\r\n * @returns {}\r\n */\r\nexport const canDeleteModel = (models, modelId) => {\r\n const errors = []\r\n\r\n for (let model of models) {\r\n const links = model.fields.filter(\r\n f => f.type === \"link\" && f.typeOptions.modelId === modelId\r\n )\r\n\r\n for (let link of links) {\r\n errors.push(\r\n `The \"${model.name}\" model links to this model, via field \"${link.name}\"`\r\n )\r\n }\r\n }\r\n\r\n return {\r\n errors,\r\n canDelete: errors.length > 0,\r\n }\r\n}\r\n"],"file":"models.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/array.js.map b/packages/common/lib/schema/types/array.js.map index 056ecd769d..fd7a9761e2 100644 --- a/packages/common/lib/schema/types/array.js.map +++ b/packages/common/lib/schema/types/array.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/schema/types/array.js"],"names":["arrayFunctions","mapToParsedArrary","type","i","safeParseValue","parsedSuccess","arrayTryParse","isArray","defaultCase","parsedFailed","typeName","options","maxLength","defaultValue","isValid","isSafeInteger","requirementDescription","parse","toNumberOrNull","minLength","n","typeConstraints","val","opts","length","name","sampleValue","JSON","stringify"],"mappings":"uGAAA;AACA;;;;;;;AAOA;;;;;;;;AAQA,IAAMA,cAAc,GAAG,SAAjBA,cAAiB;AACrB,oCAAc;AACZ,iBAAS,kBAAS,EAAT,CADG,EAAd,CADqB,GAAvB;;;AAKA,IAAMC,iBAAiB,GAAG,SAApBA,iBAAoB,CAAAC,IAAI;AAC5B;AACE,iBAAI,UAAAC,CAAC,UAAID,IAAI,CAACE,cAAL,CAAoBD,CAApB,CAAJ,EAAL,CADF;AAEEE,8BAFF,CAD4B,GAA9B;;;AAMA,IAAMC,aAAa,GAAG,SAAhBA,aAAgB,CAAAJ,IAAI;AACxB,2BAAW,CAACK,WAAD,EAAUN,iBAAiB,CAACC,IAAD,CAA3B,CAAX,EAA+C,CAACM,kBAAD,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P,CADiB,G","sourcesContent":["import { map, constant, isArray } from \"lodash/fp\"\nimport {\n typeFunctions,\n makerule,\n parsedFailed,\n getDefaultExport,\n parsedSuccess,\n} from \"./typeHelpers\"\nimport {\n switchCase,\n defaultCase,\n toNumberOrNull,\n $$,\n isSafeInteger,\n} from \"../../common/index.js\"\n\nconst arrayFunctions = () =>\n typeFunctions({\n default: constant([]),\n })\n\nconst mapToParsedArrary = type =>\n $$(\n map(i => type.safeParseValue(i)),\n parsedSuccess\n )\n\nconst arrayTryParse = type =>\n switchCase([isArray, mapToParsedArrary(type)], [defaultCase, parsedFailed])\n\nconst typeName = type => `array<${type}>`\n\nconst options = {\n maxLength: {\n defaultValue: 10000,\n isValid: isSafeInteger,\n requirementDescription: \"must be a positive integer\",\n parse: toNumberOrNull,\n },\n minLength: {\n defaultValue: 0,\n isValid: n => isSafeInteger(n) && n >= 0,\n requirementDescription: \"must be a positive integer\",\n parse: toNumberOrNull,\n },\n}\n\nconst typeConstraints = [\n makerule(\n (val, opts) => val === null || val.length >= opts.minLength,\n (val, opts) => `must choose ${opts.minLength} or more options`\n ),\n makerule(\n (val, opts) => val === null || val.length <= opts.maxLength,\n (val, opts) => `cannot choose more than ${opts.maxLength} options`\n ),\n]\n\nexport default type =>\n getDefaultExport(\n typeName(type.name),\n arrayTryParse(type),\n arrayFunctions(type),\n options,\n typeConstraints,\n [type.sampleValue],\n JSON.stringify\n )\n"],"file":"array.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/schema/types/array.js"],"names":["arrayFunctions","mapToParsedArrary","type","i","safeParseValue","parsedSuccess","arrayTryParse","isArray","defaultCase","parsedFailed","typeName","options","maxLength","defaultValue","isValid","isSafeInteger","requirementDescription","parse","toNumberOrNull","minLength","n","typeConstraints","val","opts","length","name","sampleValue","JSON","stringify"],"mappings":"uGAAA;AACA;;;;;;;AAOA;;;;;;;;AAQA,IAAMA,cAAc,GAAG,SAAjBA,cAAiB;AACrB,oCAAc;AACZ,iBAAS,kBAAS,E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;AAEE,UAACU,GAAD,EAAMC,IAAN,4CAA0CA,IAAI,CAACX,SAA/C,eAFF,CALsB,CAAxB,C;;;;AAWe,kBAAAV,IAAI;AACjB;AACEQ,IAAAA,QAAQ,CAACR,IAAI,CAACuB,IAAN,CADV;AAEEnB,IAAAA,aAAa,CAACJ,IAAD,CAFf;AAGEF,IAAAA,cAAc,CAACE,IAAD,CAHhB;AAIES,IAAAA,OAJF;AAKEU,IAAAA,eALF;AAME,KAACnB,IAAI,CAACwB,WAAN,CANF;AAOEC,IAAAA,IAAI,CAACC,SAPP,CADiB,G","sourcesContent":["import { map, constant, isArray } from \"lodash/fp\"\r\nimport {\r\n typeFunctions,\r\n makerule,\r\n parsedFailed,\r\n getDefaultExport,\r\n parsedSuccess,\r\n} from \"./typeHelpers\"\r\nimport {\r\n switchCase,\r\n defaultCase,\r\n toNumberOrNull,\r\n $$,\r\n isSafeInteger,\r\n} from \"../../common/index.js\"\r\n\r\nconst arrayFunctions = () =>\r\n typeFunctions({\r\n default: constant([]),\r\n })\r\n\r\nconst mapToParsedArrary = type =>\r\n $$(\r\n map(i => type.safeParseValue(i)),\r\n parsedSuccess\r\n )\r\n\r\nconst arrayTryParse = type =>\r\n switchCase([isArray, mapToParsedArrary(type)], [defaultCase, parsedFailed])\r\n\r\nconst typeName = type => `array<${type}>`\r\n\r\nconst options = {\r\n maxLength: {\r\n defaultValue: 10000,\r\n isValid: isSafeInteger,\r\n requirementDescription: \"must be a positive integer\",\r\n parse: toNumberOrNull,\r\n },\r\n minLength: {\r\n defaultValue: 0,\r\n isValid: n => isSafeInteger(n) && n >= 0,\r\n requirementDescription: \"must be a positive integer\",\r\n parse: toNumberOrNull,\r\n },\r\n}\r\n\r\nconst typeConstraints = [\r\n makerule(\r\n (val, opts) => val === null || val.length >= opts.minLength,\r\n (val, opts) => `must choose ${opts.minLength} or more options`\r\n ),\r\n makerule(\r\n (val, opts) => val === null || val.length <= opts.maxLength,\r\n (val, opts) => `cannot choose more than ${opts.maxLength} options`\r\n ),\r\n]\r\n\r\nexport default type =>\r\n getDefaultExport(\r\n typeName(type.name),\r\n arrayTryParse(type),\r\n arrayFunctions(type),\r\n options,\r\n typeConstraints,\r\n [type.sampleValue],\r\n JSON.stringify\r\n )\r\n"],"file":"array.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/bool.js.map b/packages/common/lib/schema/types/bool.js.map index 749e49a9c1..33a028f904 100644 --- a/packages/common/lib/schema/types/bool.js.map +++ b/packages/common/lib/schema/types/bool.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/schema/types/bool.js"],"names":["boolFunctions","boolTryParse","isBoolean","parsedSuccess","isNull","defaultCase","parsedFailed","options","allowNulls","defaultValue","isValid","requirementDescription","parse","toBoolOrNull","typeConstraints","val","opts","JSON","stringify"],"mappings":"uGAAA;AACA;;;;;;;AAOA;;;;;;;AAOA,IAAMA,aAAa,GAAG,gCAAc;AAClC,aAAS,kBAAS,IAAT,CADyB,EAAd,CAAtB;;;AAIA,IAAMC,YAAY,GAAG;AACnB,CAACC,aAAD,EAAYC,0BAAZ,CADmB;AAEnB,CAACC,UAAD,EAASD,0BAAT,CAFmB;AAGnB,CAAC,oBAAQ,MAAR,EAAgB,GAAhB,EAAqB,KAArB,EAA4B,IAA5B,CAAD,EAAoC,oBAAM,gCAAc,IAAd,CAAN,EAApC,CAHmB;AAInB,CAAC,oBAAQ,OAAR,EAAiB,GAAjB,EAAsB,IAAtB,EAA4B,KAA5B,CAAD,EAAqC,oBAAM,gCAAc,KAAd,CAAN,EAArC,CAJmB;AAKnB,CAACE,kBAAD,EAAcC,yBAAd,CALmB,CAArB;;;AAQA,IAAMC,OAAO,GAAG;AACdC,EAAAA,UAAU,EAAE;AACVC,IAAAA,YAAY,EAAE,IADJ;AAEVC,IAAAA,OAAO,EAAER,aAFC;AAGVS,IAAAA,sBAAsB,EAAE,yBAHd;AAIVC,IAAAA,KAAK,EAAEC,mBAJG,EADE,EAAhB;;;;AASA,IAAMC,eAAe,GAAG;AACtB;AACE,UAACC,GAAD,EAAMC,IAAN,UAAeA,IAAI,CAACR,UAAL,KAAoB,IAApB,IAA4BO,GAAG,KAAK,IAAnD,EADF;AAEE,oBAAM,sBAAN,EAFF,CADsB,CAAxB,C;;;;AAOe;AACb,MADa;AAEbd,YAFa;AAGbD,aAHa;AAIbO,OAJa;AAKbO,eALa;AAMb,IANa;AAObG,IAAI,CAACC,SAPQ,C","sourcesContent":["import { constant, isBoolean, isNull } from \"lodash/fp\"\nimport {\n typeFunctions,\n makerule,\n parsedFailed,\n parsedSuccess,\n getDefaultExport,\n} from \"./typeHelpers\"\nimport {\n switchCase,\n defaultCase,\n isOneOf,\n toBoolOrNull,\n} from \"../../common/index.js\"\n\nconst boolFunctions = typeFunctions({\n default: constant(null),\n})\n\nconst boolTryParse = switchCase(\n [isBoolean, parsedSuccess],\n [isNull, parsedSuccess],\n [isOneOf(\"true\", \"1\", \"yes\", \"on\"), () => parsedSuccess(true)],\n [isOneOf(\"false\", \"0\", \"no\", \"off\"), () => parsedSuccess(false)],\n [defaultCase, parsedFailed]\n)\n\nconst options = {\n allowNulls: {\n defaultValue: true,\n isValid: isBoolean,\n requirementDescription: \"must be a true or false\",\n parse: toBoolOrNull,\n },\n}\n\nconst typeConstraints = [\n makerule(\n (val, opts) => opts.allowNulls === true || val !== null,\n () => \"field cannot be null\"\n ),\n]\n\nexport default getDefaultExport(\n \"bool\",\n boolTryParse,\n boolFunctions,\n options,\n typeConstraints,\n true,\n JSON.stringify\n)\n"],"file":"bool.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/schema/types/bool.js"],"names":["boolFunctions","boolTryParse","isBoolean","parsedSuccess","isNull","defaultCase","parsedFailed","options","allowNulls","defaultValue","isValid","requirementDescription","parse","toBoolOrNull","typeConstraints","val","opts","JSON","stringify"],"mappings":"uGAAA;AACA;;;;;;;AAOA;;;;;;;AAOA,IAAMA,aAAa,GAAG,gCAAc;AAClC,aAAS,kBAAS,IAAT,CADyB,EAAd,CAAtB;;;AAIA,IAAMC,YAAY,GAAG;AACnB,CAACC,aAAD,EAAYC,0BAAZ,CADmB;AAEnB,CAACC,UAAD,EAASD,0BAAT,CAFmB;AAGnB,CAAC,oBAAQ,MAAR,EAAgB,GAAhB,EAAqB,KAArB,EAA4B,IAA5B,CAAD,EAAoC,oBAAM,gCAAc,IAAd,CAAN,EAApC,CAHmB;AAInB,CAAC,oBAAQ,OAAR,EAAiB,GAAjB,EAAsB,IAAtB,EAA4B,KAA5B,CAAD,EAAqC,oBAAM,gCAAc,KAAd,CAAN,EAArC,CAJmB;AAKnB,CAACE,kBAAD,EAAcC,yBAAd,CALmB,CAArB;;;AAQA,IAAMC,OAAO,GAAG;AACdC,EAAAA,UAAU,EAAE;AACVC,IAAAA,YAAY,EAAE,IADJ;AAEVC,IAAAA,OAAO,EAAER,aAFC;AAGVS,IAAAA,sBAAsB,EAAE,yBAHd;AAIVC,IAAAA,KAAK,EAAEC,mBAJG,EADE,EAAhB;;;;AASA,IAAMC,eAAe,GAAG;AACtB;AACE,UAACC,GAAD,EAAMC,IAAN,UAAeA,IAAI,CAACR,UAAL,KAAoB,IAApB,IAA4BO,GAAG,KAAK,IAAnD,EADF;AAEE,oBAAM,sBAAN,EAFF,CADsB,CAAxB,C;;;;AAOe;AACb,MADa;AAEbd,YAFa;AAGbD,aAHa;AAIbO,OAJa;AAKbO,eALa;AAMb,IANa;AAObG,IAAI,CAACC,SAPQ,C","sourcesContent":["import { constant, isBoolean, isNull } from \"lodash/fp\"\r\nimport {\r\n typeFunctions,\r\n makerule,\r\n parsedFailed,\r\n parsedSuccess,\r\n getDefaultExport,\r\n} from \"./typeHelpers\"\r\nimport {\r\n switchCase,\r\n defaultCase,\r\n isOneOf,\r\n toBoolOrNull,\r\n} from \"../../common/index.js\"\r\n\r\nconst boolFunctions = typeFunctions({\r\n default: constant(null),\r\n})\r\n\r\nconst boolTryParse = switchCase(\r\n [isBoolean, parsedSuccess],\r\n [isNull, parsedSuccess],\r\n [isOneOf(\"true\", \"1\", \"yes\", \"on\"), () => parsedSuccess(true)],\r\n [isOneOf(\"false\", \"0\", \"no\", \"off\"), () => parsedSuccess(false)],\r\n [defaultCase, parsedFailed]\r\n)\r\n\r\nconst options = {\r\n allowNulls: {\r\n defaultValue: true,\r\n isValid: isBoolean,\r\n requirementDescription: \"must be a true or false\",\r\n parse: toBoolOrNull,\r\n },\r\n}\r\n\r\nconst typeConstraints = [\r\n makerule(\r\n (val, opts) => opts.allowNulls === true || val !== null,\r\n () => \"field cannot be null\"\r\n ),\r\n]\r\n\r\nexport default getDefaultExport(\r\n \"bool\",\r\n boolTryParse,\r\n boolFunctions,\r\n options,\r\n typeConstraints,\r\n true,\r\n JSON.stringify\r\n)\r\n"],"file":"bool.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/datetime.js b/packages/common/lib/schema/types/datetime.js index 5fcaa8f0f7..982e98bdb7 100644 --- a/packages/common/lib/schema/types/datetime.js +++ b/packages/common/lib/schema/types/datetime.js @@ -1,78 +1,18 @@ -"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _fp = require("lodash/fp"); -var _typeHelpers = require("./typeHelpers"); +"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _default2 = { + isType: function isType(schema) {return ( + schema.anyOf && + schema.anyOf.filter(function (s) {return s.type === "string" && s.format === "date-time";}). + length > 0);}, + fromSchema: function fromSchema(schema) {return { + type: "datetime", + "default": schema["default"] };}, + toSchema: function toSchema() {return { + anyOf: [{ type: "string", format: "date-time" }, { "const": "" }], + "default": "" };}, - - - -var _common = require("../../common"); - -var dateFunctions = (0, _typeHelpers.typeFunctions)({ - "default": (0, _fp.constant)(null), - now: function now() {return new Date();} }); - - -var isValidDate = function isValidDate(d) {return d instanceof Date && !isNaN(d);}; - -var parseStringToDate = function parseStringToDate(s) {return ( - (0, _common.switchCase)( - [isValidDate, _typeHelpers.parsedSuccess], - [_common.defaultCase, _typeHelpers.parsedFailed])( - new Date(s)));}; - -var isNullOrEmpty = function isNullOrEmpty(d) {return (0, _fp.isNull)(d) || (d || "").toString() === "";}; - -var isDateOrEmpty = function isDateOrEmpty(d) {return (0, _fp.isDate)(d) || isNullOrEmpty(d);}; - -var dateTryParse = (0, _common.switchCase)( -[isDateOrEmpty, _typeHelpers.parsedSuccess], -[_fp.isString, parseStringToDate], -[_common.defaultCase, _typeHelpers.parsedFailed]); - - -var options = { - maxValue: { - defaultValue: null, - //defaultValue: new Date(32503680000000), - isValid: isDateOrEmpty, - requirementDescription: "must be a valid date", - parse: _common.toDateOrNull }, - - minValue: { - defaultValue: null, - //defaultValue: new Date(-8520336000000), - isValid: isDateOrEmpty, - requirementDescription: "must be a valid date", - parse: _common.toDateOrNull } }; - - - -var typeConstraints = [ -(0, _typeHelpers.makerule)( -function (val, opts) {return ( - val === null || isNullOrEmpty(opts.minValue) || val >= opts.minValue);}, -function (val, opts) {return "value (".concat( - val.toString(), ") must be greater than or equal to ").concat( - opts.minValue);}), - - -(0, _typeHelpers.makerule)( -function (val, opts) {return ( - val === null || isNullOrEmpty(opts.maxValue) || val <= opts.maxValue);}, -function (val, opts) {return "value (".concat( - val.toString(), ") must be less than or equal to ").concat( - opts.minValue, " options");})];var _default = - - - - -(0, _typeHelpers.getDefaultExport)( -"datetime", -dateTryParse, -dateFunctions, -options, -typeConstraints, -new Date(1984, 4, 1), -function (date) {return JSON.stringify(date).replace(new RegExp('"', "g"), "");});exports["default"] = _default; + "default": function _default() {return { + type: "datetime", + "default": "" };} };exports["default"] = _default2; //# sourceMappingURL=datetime.js.map \ No newline at end of file diff --git a/packages/common/lib/schema/types/datetime.js.map b/packages/common/lib/schema/types/datetime.js.map index 6559a7758e..bd3f1e0271 100644 --- a/packages/common/lib/schema/types/datetime.js.map +++ b/packages/common/lib/schema/types/datetime.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/schema/types/datetime.js"],"names":["dateFunctions","now","Date","isValidDate","d","isNaN","parseStringToDate","s","parsedSuccess","defaultCase","parsedFailed","isNullOrEmpty","toString","isDateOrEmpty","dateTryParse","isString","options","maxValue","defaultValue","isValid","requirementDescription","parse","toDateOrNull","minValue","typeConstraints","val","opts","date","JSON","stringify","replace","RegExp"],"mappings":"uGAAA;AACA;;;;;;;AAOA;;AAEA,IAAMA,aAAa,GAAG,gCAAc;AAClC,aAAS,kBAAS,IAAT,CADyB;AAElCC,EAAAA,GAAG,EAAE,uBAAM,IAAIC,IAAJ,EAAN,EAF6B,EAAd,CAAtB;;;AAKA,IAAMC,WAAW,GAAG,SAAdA,WAAc,CAAAC,CAAC,UAAIA,CAAC,YAAYF,IAAb,IAAqB,CAACG,KAAK,CAACD,CAAD,CAA/B,EAArB;;AAEA,IAAME,iBAAiB,GAAG,SAApBA,iBAAoB,CAAAC,CAAC;AACzB;AACE,KAACJ,WAAD,EAAcK,0BAAd,CADF;AAEE,KAACC,mBAAD,EAAcC,yBAAd,CAFF;AAGE,QAAIR,IAAJ,CAASK,CAAT,CAHF,CADyB,GAA3B;;AAMA,IAAMI,aAAa,GAAG,SAAhBA,aAAgB,CAAAP,CAAC,UAAI,gBAAOA,CAAP,KAAa,CAACA,CAAC,IAAI,EAAN,EAAUQ,QAAV,OAAyB,EAA1C,EAAvB;;AAEA,IAAMC,aAAa,GAAG,SAAhBA,aAAgB,CAAAT,CAAC,UAAI,gBAAOA,CAAP,KAAaO,aAAa,CAACP,CAAD,CAA9B,EAAvB;;AAEA,IAAMU,YAAY,GAAG;AACnB,CAACD,aAAD,EAAgBL,0BAAhB,CADmB;AAEnB,CAACO,YAAD,EAAWT,iBAAX,CAFmB;AAGnB,CAACG,mBAAD,EAAcC,yBAAd,CAHmB,CAArB;;;AAMA,IAAMM,OAAO,GAAG;AACdC,EAAAA,QAAQ,EAAE;AACRC,IAAAA,YAAY,EAAE,IADN;AAER;AACAC,IAAAA,OAAO,EAAEN,aAHD;AAIRO,IAAAA,sBAAsB,EAAE,sBAJhB;AAKRC,IAAAA,KAAK,EAAEC,oBALC,EADI;;AAQdC,EAAAA,QAAQ,EAAE;AACRL,IAAAA,YAAY,EAAE,IADN;AAER;AACAC,IAAAA,OAAO,EAAEN,aAHD;AAIRO,IAAAA,sBAAsB,EAAE,sBAJhB;AAKRC,IAAAA,KAAK,EAAEC,oBALC,EARI,EAAhB;;;;AAiBA,IAAME,eAAe,GAAG;AACtB;AACE,UAACC,GAAD,EAAMC,IAAN;AACED,IAAAA,GAAG,KAAK,IAAR,IAAgBd,aAAa,CAACe,IAAI,CAACH,QAAN,CAA7B,IAAgDE,GAAG,IAAIC,IAAI,CAACH,QAD9D,GADF;AAGE,UAACE,GAAD,EAAMC,IAAN;AACYD,EAAAA,GAAG,CAACb,QAAJ,EADZ;AAEIc,EAAAA,IAAI,CAACH,QAFT,GAHF,CADsB;;;AAStB;AACE,UAACE,GAAD,EAAMC,IAAN;AACED,IAAAA,GAAG,KAAK,IAAR,IAAgBd,aAAa,CAACe,IAAI,CAACT,QAAN,CAA7B,IAAgDQ,GAAG,IAAIC,IAAI,CAACT,QAD9D,GADF;AAGE,UAACQ,GAAD,EAAMC,IAAN;AACYD,EAAAA,GAAG,CAACb,QAAJ,EADZ;AAEIc,EAAAA,IAAI,CAACH,QAFT,eAHF,CATsB,CAAxB,C;;;;;AAmBe;AACb,UADa;AAEbT,YAFa;AAGbd,aAHa;AAIbgB,OAJa;AAKbQ,eALa;AAMb,IAAItB,IAAJ,CAAS,IAAT,EAAe,CAAf,EAAkB,CAAlB,CANa;AAOb,UAAAyB,IAAI,UAAIC,IAAI,CAACC,SAAL,CAAeF,IAAf,EAAqBG,OAArB,CAA6B,IAAIC,MAAJ,CAAW,GAAX,EAAgB,GAAhB,CAA7B,EAAmD,EAAnD,CAAJ,EAPS,C","sourcesContent":["import { constant, isDate, isString, isNull } from \"lodash/fp\"\nimport {\n makerule,\n typeFunctions,\n parsedFailed,\n parsedSuccess,\n getDefaultExport,\n} from \"./typeHelpers\"\nimport { switchCase, defaultCase, toDateOrNull } from \"../../common\"\n\nconst dateFunctions = typeFunctions({\n default: constant(null),\n now: () => new Date(),\n})\n\nconst isValidDate = d => d instanceof Date && !isNaN(d)\n\nconst parseStringToDate = s =>\n switchCase(\n [isValidDate, parsedSuccess],\n [defaultCase, parsedFailed]\n )(new Date(s))\n\nconst isNullOrEmpty = d => isNull(d) || (d || \"\").toString() === \"\"\n\nconst isDateOrEmpty = d => isDate(d) || isNullOrEmpty(d)\n\nconst dateTryParse = switchCase(\n [isDateOrEmpty, parsedSuccess],\n [isString, parseStringToDate],\n [defaultCase, parsedFailed]\n)\n\nconst options = {\n maxValue: {\n defaultValue: null,\n //defaultValue: new Date(32503680000000),\n isValid: isDateOrEmpty,\n requirementDescription: \"must be a valid date\",\n parse: toDateOrNull,\n },\n minValue: {\n defaultValue: null,\n //defaultValue: new Date(-8520336000000),\n isValid: isDateOrEmpty,\n requirementDescription: \"must be a valid date\",\n parse: toDateOrNull,\n },\n}\n\nconst typeConstraints = [\n makerule(\n (val, opts) =>\n val === null || isNullOrEmpty(opts.minValue) || val >= opts.minValue,\n (val, opts) =>\n `value (${val.toString()}) must be greater than or equal to ${\n opts.minValue\n }`\n ),\n makerule(\n (val, opts) =>\n val === null || isNullOrEmpty(opts.maxValue) || val <= opts.maxValue,\n (val, opts) =>\n `value (${val.toString()}) must be less than or equal to ${\n opts.minValue\n } options`\n ),\n]\n\nexport default getDefaultExport(\n \"datetime\",\n dateTryParse,\n dateFunctions,\n options,\n typeConstraints,\n new Date(1984, 4, 1),\n date => JSON.stringify(date).replace(new RegExp('\"', \"g\"), \"\")\n)\n"],"file":"datetime.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/schema/types/datetime.js"],"names":["isType","schema","anyOf","filter","s","type","format","length","fromSchema","toSchema"],"mappings":"uHAAe;AACbA,EAAAA,MAAM,EAAE,gBAAAC,MAAM;AACZA,MAAAA,MAAM,CAACC,KAAP;AACAD,MAAAA,MAAM,CAACC,KAAP,CAAaC,MAAb,CAAoB,UAAAC,CAAC,UAAIA,CAAC,CAACC,IAAF,KAAW,QAAX,IAAuBD,CAAC,CAACE,MAAF,KAAa,WAAxC,EAArB;AACGC,MAAAA,MADH,GACY,CAHA,GADD;;AAMbC,EAAAA,UAAU,EAAE,oBAAAP,MAAM,UAAK;AACrBI,MAAAA,IAAI,EAAE,UADe;AAErB,iBAASJ,MAAM,WAFM,EAAL,EANL;;AAUbQ,EAAAA,QAAQ,EAAE,4BAAO;AACfP,MAAAA,KAAK,EAAE,CAAC,EAAEG,IAAI,EAAE,QAAR,EAAkBC,MAAM,EAAE,WAA1B,EAAD,EAA0C,EAAE,SAAO,EAAT,EAA1C,CADQ;AAEf,iBAAS,EAFM,EAAP,EAVG;;AAcb,aAAS,4BAAO;AACdD,MAAAA,IAAI,EAAE,UADQ;AAEd,iBAAS,EAFK,EAAP,EAdI,E","sourcesContent":["export default {\r\n isType: schema =>\r\n schema.anyOf &&\r\n schema.anyOf.filter(s => s.type === \"string\" && s.format === \"date-time\")\r\n .length > 0,\r\n\r\n fromSchema: schema => ({\r\n type: \"datetime\",\r\n default: schema.default,\r\n }),\r\n toSchema: () => ({\r\n anyOf: [{ type: \"string\", format: \"date-time\" }, { const: \"\" }],\r\n default: \"\",\r\n }),\r\n default: () => ({\r\n type: \"datetime\",\r\n default: \"\",\r\n }),\r\n}\r\n"],"file":"datetime.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/file.js.map b/packages/common/lib/schema/types/file.js.map index c08e34a911..17b9a9fc52 100644 --- a/packages/common/lib/schema/types/file.js.map +++ b/packages/common/lib/schema/types/file.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/schema/types/file.js"],"names":["illegalCharacters","isLegalFilename","filePath","fn","fileName","length","split","f","fileNothing","relativePath","size","fileFunctions","fileTryParse","v","isValidFile","parsedSuccess","isNull","defaultCase","parsedFailed","splitKey","last","options","typeConstraints","JSON","stringify"],"mappings":"iIAAA;AACA;;;;;;AAMA;;;;;;;;AAQA,IAAMA,iBAAiB,GAAG,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YAAH,CANI,GAArB;;AAQA,IAAMY,OAAO,GAAG,EAAhB;;AAEA,IAAMC,eAAe,GAAG,EAAxB,C;;AAEe;AACb,MADa;AAEbV,YAFa;AAGbD,aAHa;AAIbU,OAJa;AAKbC,eALa;AAMb,EAAEb,YAAY,EAAE,eAAhB,EAAiCC,IAAI,EAAE,IAAvC,EANa;AAOba,IAAI,CAACC,SAPQ,C","sourcesContent":["import { last, has, isString, intersection, isNull, isNumber } from \"lodash/fp\"\nimport {\n typeFunctions,\n parsedFailed,\n parsedSuccess,\n getDefaultExport,\n} from \"./typeHelpers\"\nimport {\n switchCase,\n defaultCase,\n none,\n $,\n splitKey,\n} from \"../../common/index.js\"\n\nconst illegalCharacters = \"*?\\\\/:<>|\\0\\b\\f\\v\"\n\nexport const isLegalFilename = filePath => {\n const fn = fileName(filePath)\n return (\n fn.length <= 255 &&\n intersection(fn.split(\"\"))(illegalCharacters.split(\"\")).length === 0 &&\n none(f => f === \"..\")(splitKey(filePath))\n )\n}\n\nconst fileNothing = () => ({ relativePath: \"\", size: 0 })\n\nconst fileFunctions = typeFunctions({\n default: fileNothing,\n})\n\nconst fileTryParse = v =>\n switchCase(\n [isValidFile, parsedSuccess],\n [isNull, () => parsedSuccess(fileNothing())],\n [defaultCase, parsedFailed]\n )(v)\n\nconst fileName = filePath => $(filePath, [splitKey, last])\n\nconst isValidFile = f =>\n !isNull(f) &&\n has(\"relativePath\")(f) &&\n has(\"size\")(f) &&\n isNumber(f.size) &&\n isString(f.relativePath) &&\n isLegalFilename(f.relativePath)\n\nconst options = {}\n\nconst typeConstraints = []\n\nexport default getDefaultExport(\n \"file\",\n fileTryParse,\n fileFunctions,\n options,\n typeConstraints,\n { relativePath: \"some_file.jpg\", size: 1000 },\n JSON.stringify\n)\n"],"file":"file.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/schema/types/file.js"],"names":["illegalCharacters","isLegalFilename","filePath","fn","fileName","length","split","f","fileNothing","relativePath","size","fileFunctions","fileTryParse","v","isValidFile","parsedSuccess","isNull","defaultCase","parsedFailed","splitKey","last","options","typeConstraints","JSON","stringify"],"mappings":"iIAAA;AACA;;;;;;AAMA;;;;;;;;AAQA,IAAMA,iBAAiB,GAAG,mBAA1B;;AAEO,IAAMC,eAAe,GAAG,SAAlBA,eAAkB,CAAAC,QAAQ,EAAI;AACzC,MAAMC,EAAE,GAAGC,QAAQ,CAACF,QAAD,CAAnB;AACA;AACEC,IAAAA,EAAE,CAACE,MAAH,IAAa,GAAb;AACA,0BAAaF,EAAE,CAACG,KAAH,CAAS,EAAT,CAAb,EAA2BN,iBAAiB,CAACM,KAAlB,CAAwB,EAAxB,CAA3B,EAAwDD,MAAxD,KAAmE,CADnE;AAEA,qBAAK,UAAAE,CAAC,UAAIA,CAAC,KAAK,IAAV,EAAN,EAAsB,qBAASL,QAAT,CAAtB,CAHF;;AAKD,CAPM,C;;AASP,IAAMM,WAAW,GAAG,SAAdA,WAAc,WAAO,EAAEC,YAAY,EAAE,EAAhB,EAAoBC,IAAI,EAAE,CAA1B,EAAP,EAApB;;AAEA,IAAMC,aAAa,GAAG,gCAAc;AAClC,aAASH,WADyB,EAAd,CAAtB;;;AAIA,IAAMI,YAAY,GAAG,SAAfA,YAAe,CAAAC,CAAC;AACpB;AACE,KAACC,WAAD,EAAcC,0BAAd,CADF;AAEE,KAACC,UAAD,EAAS,oBAAM,gCAAcR,WAAW,EAAzB,CAAN,EAAT,CAFF;AAGE,KAACS,kBAAD,EAAcC,yBAAd,CAHF;AAIEL,IAAAA,CAJF,CADoB,GAAtB;;AAOA,IAAMT,QAAQ,GAAG,SAAXA,QAAW,CAAAF,QAAQ,UAAI,cAAEA,QAAF,EAAY,CAACiB,eAAD,EAAWC,QAAX,CAAZ,CAAJ,EAAzB;;AAEA,IAAMN,WAAW,GAAG,SAAdA,WAAc,CAAAP,CAAC;AACnB,KAAC,gBAAOA,CAAP,CAAD;AACA,iBAAI,cAAJ,EAAoBA,CAApB,CADA;AAEA,iBAAI,MAAJ,EAAYA,CAAZ,CAFA;AAGA,sBAASA,CAAC,CAACG,IAAX,CAHA;AAIA,sBAASH,CAAC,CAACE,YAAX,CAJA;AAKAR,IAAAA,eAAe,CAACM,CAAC,CAACE,YAAH,CANI,GAArB;;AAQA,IAAMY,OAAO,GAAG,EAAhB;;AAEA,IAAMC,eAAe,GAAG,EAAxB,C;;AAEe;AACb,MADa;AAEbV,YAFa;AAGbD,aAHa;AAIbU,OAJa;AAKbC,eALa;AAMb,EAAEb,YAAY,EAAE,eAAhB,EAAiCC,IAAI,EAAE,IAAvC,EANa;AAOba,IAAI,CAACC,SAPQ,C","sourcesContent":["import { last, has, isString, intersection, isNull, isNumber } from \"lodash/fp\"\r\nimport {\r\n typeFunctions,\r\n parsedFailed,\r\n parsedSuccess,\r\n getDefaultExport,\r\n} from \"./typeHelpers\"\r\nimport {\r\n switchCase,\r\n defaultCase,\r\n none,\r\n $,\r\n splitKey,\r\n} from \"../../common/index.js\"\r\n\r\nconst illegalCharacters = \"*?\\\\/:<>|\\0\\b\\f\\v\"\r\n\r\nexport const isLegalFilename = filePath => {\r\n const fn = fileName(filePath)\r\n return (\r\n fn.length <= 255 &&\r\n intersection(fn.split(\"\"))(illegalCharacters.split(\"\")).length === 0 &&\r\n none(f => f === \"..\")(splitKey(filePath))\r\n )\r\n}\r\n\r\nconst fileNothing = () => ({ relativePath: \"\", size: 0 })\r\n\r\nconst fileFunctions = typeFunctions({\r\n default: fileNothing,\r\n})\r\n\r\nconst fileTryParse = v =>\r\n switchCase(\r\n [isValidFile, parsedSuccess],\r\n [isNull, () => parsedSuccess(fileNothing())],\r\n [defaultCase, parsedFailed]\r\n )(v)\r\n\r\nconst fileName = filePath => $(filePath, [splitKey, last])\r\n\r\nconst isValidFile = f =>\r\n !isNull(f) &&\r\n has(\"relativePath\")(f) &&\r\n has(\"size\")(f) &&\r\n isNumber(f.size) &&\r\n isString(f.relativePath) &&\r\n isLegalFilename(f.relativePath)\r\n\r\nconst options = {}\r\n\r\nconst typeConstraints = []\r\n\r\nexport default getDefaultExport(\r\n \"file\",\r\n fileTryParse,\r\n fileFunctions,\r\n options,\r\n typeConstraints,\r\n { relativePath: \"some_file.jpg\", size: 1000 },\r\n JSON.stringify\r\n)\r\n"],"file":"file.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/index.js b/packages/common/lib/schema/types/index.js index f77aeb3c4f..86a6412828 100644 --- a/packages/common/lib/schema/types/index.js +++ b/packages/common/lib/schema/types/index.js @@ -1,85 +1,54 @@ -"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports.detectType = exports.validateTypeConstraints = exports.getDefaultOptions = exports.validateFieldParse = exports.safeParseField = exports.getNewFieldValue = exports.getSampleFieldValue = exports.getType = exports.all = void 0;var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _lodash = require("lodash"); -var _fp = require("lodash/fp"); - - - - - - - - - - -var _common = require("../../common"); -var _typeHelpers = require("./typeHelpers"); -var _string = _interopRequireDefault(require("./string")); -var _bool = _interopRequireDefault(require("./bool")); -var _number = _interopRequireDefault(require("./number")); +"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports.listTypes = listTypes;exports.newField = newField;exports.fieldsToSchema = fieldsToSchema;exports.schemaToFields = schemaToFields;var _boolean2 = _interopRequireDefault(require("./boolean")); var _datetime = _interopRequireDefault(require("./datetime")); -var _array = _interopRequireDefault(require("./array")); var _link = _interopRequireDefault(require("./link")); -var _file = _interopRequireDefault(require("./file")); -var _errors = require("../../common/errors"); +var _number = _interopRequireDefault(require("./number")); +var _select = _interopRequireDefault(require("./select")); +var _text = _interopRequireDefault(require("./text")); -var allTypes = function allTypes() { - var basicTypes = { - string: _string["default"], - number: _number["default"], - datetime: _datetime["default"], - bool: _bool["default"], - link: _link["default"], - file: _file["default"] }; +var allTypes = { + "boolean": _boolean2["default"], + datetime: _datetime["default"], + link: _link["default"], + number: _number["default"], + select: _select["default"], + text: _text["default"] }; - var arrays = (0, _common.$)(basicTypes, [ - _fp.keys, - (0, _fp.map)(function (k) { - var kvType = {}; - var concreteArray = (0, _array["default"])(basicTypes[k]); - kvType[concreteArray.name] = concreteArray; - return kvType; - }), - function (types) {return _lodash.assign.apply(void 0, [{}].concat((0, _toConsumableArray2["default"])(types)));}]); +function listTypes() { + return Object.keys(allTypes); +} +function newField(name, type) { + var field = allTypes[type]["default"](); + field.name = name; + field.required = false; + return field; +} - return (0, _lodash.merge)({}, basicTypes, arrays); -}; +function fieldsToSchema(fields) { + var required = fields.filter(function (f) {return f.required;}).map(function (f) {return f.name;}); -var all = allTypes();exports.all = all; + return { + type: "object", + required: required, + properties: fields.reduce(function (sch, field) { + sch[field.name] = allTypes[field.type].toSchema(field); + return sch; + }, {}) }; -var getType = function getType(typeName) { - if (!(0, _fp.has)(typeName)(all)) - throw new _errors.BadRequestError("Do not recognise type ".concat(typeName)); - return all[typeName]; -};exports.getType = getType; +} -var getSampleFieldValue = function getSampleFieldValue(field) {return getType(field.type).sampleValue;};exports.getSampleFieldValue = getSampleFieldValue; - -var getNewFieldValue = function getNewFieldValue(field) {return getType(field.type).getNew(field);};exports.getNewFieldValue = getNewFieldValue; - -var safeParseField = function safeParseField(field, record) {return ( - getType(field.type).safeParseField(field, record));};exports.safeParseField = safeParseField; - -var validateFieldParse = function validateFieldParse(field, record) {return ( - (0, _fp.has)(field.name)(record) ? - getType(field.type).tryParse(record[field.name]) : - (0, _typeHelpers.parsedSuccess)(undefined));}; // fields may be undefined by default -exports.validateFieldParse = validateFieldParse; -var getDefaultOptions = function getDefaultOptions(type) {return getType(type).getDefaultOptions();};exports.getDefaultOptions = getDefaultOptions; - -var validateTypeConstraints = function validateTypeConstraints(field, record) {return ( - getType(field.type).validateTypeConstraints(field, record));};exports.validateTypeConstraints = validateTypeConstraints; - -var detectType = function detectType(value) { - if ((0, _fp.isString)(value)) return _string["default"]; - if ((0, _fp.isBoolean)(value)) return _bool["default"]; - if ((0, _fp.isNumber)(value)) return _number["default"]; - if ((0, _fp.isDate)(value)) return _datetime["default"]; - if ((0, _fp.isArray)(value)) return (0, _array["default"])(detectType(value[0])); - if ((0, _fp.isObject)(value) && (0, _fp.has)("key")(value) && (0, _fp.has)("value")(value)) return _link["default"]; - if ((0, _fp.isObject)(value) && (0, _fp.has)("relativePath")(value) && (0, _fp.has)("size")(value)) - return _file["default"]; - - throw new _errors.BadRequestError("cannot determine type: ".concat(JSON.stringify(value))); -};exports.detectType = detectType; +function schemaToFields(modelSchema) { + return Object.keys(modelSchema.properties).map(function (key) { + var schema = modelSchema.properties[key]; + for (var type in allTypes) { + if (allTypes[type].isType(schema)) { + var field = allTypes[type].fromSchema(schema); + field.required = modelSchema.required.includes(key); + field.name = key; + return field; + } + } + }); +} //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/common/lib/schema/types/index.js.map b/packages/common/lib/schema/types/index.js.map index 5e1aa0307c..cfebb139f9 100644 --- a/packages/common/lib/schema/types/index.js.map +++ b/packages/common/lib/schema/types/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/schema/types/index.js"],"names":["allTypes","basicTypes","string","number","datetime","bool","link","file","arrays","keys","k","kvType","concreteArray","name","types","assign","all","getType","typeName","BadRequestError","getSampleFieldValue","field","type","sampleValue","getNewFieldValue","getNew","safeParseField","record","validateFieldParse","tryParse","undefined","getDefaultOptions","validateTypeConstraints","detectType","value","JSON","stringify"],"mappings":"+eAAA;AACA;;;;;;;;;;;AAWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,IAAMA,QAAQ,GAAG,SAAXA,QAAW,GAAM;AACrB,MAAMC,UAAU,GAAG;AACjBC,IAAAA,MAAM,EAANA,kBADiB;AAEjBC,IAAAA,MAAM,EAANA,kBAFiB;AAGjBC,IAAAA,QAAQ,EAARA,oBAHiB;AAIjBC,IAAAA,IAAI,EAAJA,gBAJi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;AACE,SAAO3B,gBAAP;;AAEF,QAAM,IAAIY,uBAAJ,kCAA8CgB,IAAI,CAACC,SAAL,CAAeF,KAAf,CAA9C,EAAN;AACD,CAXM,C","sourcesContent":["import { assign, merge } from \"lodash\"\nimport {\n map,\n isString,\n isNumber,\n isBoolean,\n isDate,\n keys,\n isObject,\n isArray,\n has,\n} from \"lodash/fp\"\nimport { $ } from \"../../common\"\nimport { parsedSuccess } from \"./typeHelpers\"\nimport string from \"./string\"\nimport bool from \"./bool\"\nimport number from \"./number\"\nimport datetime from \"./datetime\"\nimport array from \"./array\"\nimport link from \"./link\"\nimport file from \"./file\"\nimport { BadRequestError } from \"../../common/errors\"\n\nconst allTypes = () => {\n const basicTypes = {\n string,\n number,\n datetime,\n bool,\n link,\n file,\n }\n\n const arrays = $(basicTypes, [\n keys,\n map(k => {\n const kvType = {}\n const concreteArray = array(basicTypes[k])\n kvType[concreteArray.name] = concreteArray\n return kvType\n }),\n types => assign({}, ...types),\n ])\n\n return merge({}, basicTypes, arrays)\n}\n\nexport const all = allTypes()\n\nexport const getType = typeName => {\n if (!has(typeName)(all))\n throw new BadRequestError(`Do not recognise type ${typeName}`)\n return all[typeName]\n}\n\nexport const getSampleFieldValue = field => getType(field.type).sampleValue\n\nexport const getNewFieldValue = field => getType(field.type).getNew(field)\n\nexport const safeParseField = (field, record) =>\n getType(field.type).safeParseField(field, record)\n\nexport const validateFieldParse = (field, record) =>\n has(field.name)(record)\n ? getType(field.type).tryParse(record[field.name])\n : parsedSuccess(undefined) // fields may be undefined by default\n\nexport const getDefaultOptions = type => getType(type).getDefaultOptions()\n\nexport const validateTypeConstraints = (field, record) =>\n getType(field.type).validateTypeConstraints(field, record)\n\nexport const detectType = value => {\n if (isString(value)) return string\n if (isBoolean(value)) return bool\n if (isNumber(value)) return number\n if (isDate(value)) return datetime\n if (isArray(value)) return array(detectType(value[0]))\n if (isObject(value) && has(\"key\")(value) && has(\"value\")(value)) return link\n if (isObject(value) && has(\"relativePath\")(value) && has(\"size\")(value))\n return file\n\n throw new BadRequestError(`cannot determine type: ${JSON.stringify(value)}`)\n}\n"],"file":"index.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/schema/types/index.js"],"names":["allTypes","datetime","link","number","select","text","listTypes","Object","keys","newField","name","type","field","required","fieldsToSchema","fields","filter","f","map","properties","reduce","sch","toSchema","schemaToFields","modelSchema","key","schema","isType","fromSchema","includes"],"mappings":"0SAAA;AACA;AACA;AACA;AACA;AACA;;AAEA,IAAMA,QAAQ,GAAG;AACf,iCADe;AAEfC,EAAAA,QAAQ,EAARA,oBAFe;AAGfC,EAAAA,IAAI,EAAJA,gBAHe;AAIfC,EAAAA,MAAM,EAANA,kBAJe;AAKfC,EAAAA,MAAM,EAANA,kBALe;AAMfC,EAAAA,IAAI,EAAJA,gBANe,EAAjB;;;AASO,SAASC,SAAT,GAAqB;AAC1B,SAAOC,MAAM,CAACC,IAAP,CAAYR,QAAZ,CAAP;AACD;;AAEM,SAASS,QAAT,CAAkBC,IAAlB,EAAwBC,IAAxB,EAA8B;AACnC,MAAMC,KAAK,GAAGZ,QAAQ,CAACW,IAAD,CAAR,aAAd;AACAC,EAAAA,KAAK,CAACF,IAAN,GAAaA,IAAb;AACAE,EAAAA,KAAK,CAACC,QAAN,GAAiB,KAAjB;AACA,SAAOD,KAAP;AACD;;AAEM,SAASE,cAAT,CAAwBC,MAAxB,EAAgC;AACrC,MAAMF,QAAQ,GAAGE,MAAM,CAACC,MAAP,CAAc,UAAAC,CAAC,UAAIA,CAAC,CAACJ,QAAN,EAAf,EAA+BK,GAA/B,CAAmC,UAAAD,CAAC,UAAIA,CAAC,CAACP,IAAN,EAApC,CAAjB;;AAEA,SAAO;AACLC,IAAAA,IAAI,EAAE,QADD;AAELE,IAAAA,QAAQ,EAARA,QAFK;AAGLM,IAAAA,UAAU,EAAEJ,MAAM,CAACK,MAAP,CAAc,UAACC,GAAD,EAAMT,KAAN,EAAgB;AACxCS,MAAAA,GAAG,CAACT,KAAK,CAACF,IAAP,CAAH,GAAkBV,QAAQ,CAACY,KAAK,CAACD,IAAP,CAAR,CAAqBW,QAArB,CAA8BV,KAA9B,CAAlB;AACA,aAAOS,GAAP;AACD,KAHW,EAGT,EAHS,CAHP,EAAP;;AAQD;;AAEM,SAASE,cAAT,CAAwBC,WAAxB,EAAqC;AAC1C,SAAOjB,MAAM,CAACC,IAAP,CAAYgB,WAAW,CAACL,UAAxB,EAAoCD,GAApC,CAAwC,UAAAO,GAAG,EAAI;AACpD,QAAMC,MAAM,GAAGF,WAAW,CAACL,UAAZ,CAAuBM,GAAvB,CAAf;AACA,SAAK,IAAId,IAAT,IAAiBX,QAAjB,EAA2B;AACzB,UAAIA,QAAQ,CAACW,IAAD,CAAR,CAAegB,MAAf,CAAsBD,MAAtB,CAAJ,EAAmC;AACjC,YAAMd,KAAK,GAAGZ,QAAQ,CAACW,IAAD,CAAR,CAAeiB,UAAf,CAA0BF,MAA1B,CAAd;AACAd,QAAAA,KAAK,CAACC,QAAN,GAAiBW,WAAW,CAACX,QAAZ,CAAqBgB,QAArB,CAA8BJ,GAA9B,CAAjB;AACAb,QAAAA,KAAK,CAACF,IAAN,GAAae,GAAb;AACA,eAAOb,KAAP;AACD;AACF;AACF,GAVM,CAAP;AAWD","sourcesContent":["import boolean from \"./boolean\"\r\nimport datetime from \"./datetime\"\r\nimport link from \"./link\"\r\nimport number from \"./number\"\r\nimport select from \"./select\"\r\nimport text from \"./text\"\r\n\r\nconst allTypes = {\r\n boolean,\r\n datetime,\r\n link,\r\n number,\r\n select,\r\n text,\r\n}\r\n\r\nexport function listTypes() {\r\n return Object.keys(allTypes)\r\n}\r\n\r\nexport function newField(name, type) {\r\n const field = allTypes[type].default()\r\n field.name = name\r\n field.required = false\r\n return field\r\n}\r\n\r\nexport function fieldsToSchema(fields) {\r\n const required = fields.filter(f => f.required).map(f => f.name)\r\n\r\n return {\r\n type: \"object\",\r\n required,\r\n properties: fields.reduce((sch, field) => {\r\n sch[field.name] = allTypes[field.type].toSchema(field)\r\n return sch\r\n }, {}),\r\n }\r\n}\r\n\r\nexport function schemaToFields(modelSchema) {\r\n return Object.keys(modelSchema.properties).map(key => {\r\n const schema = modelSchema.properties[key]\r\n for (let type in allTypes) {\r\n if (allTypes[type].isType(schema)) {\r\n const field = allTypes[type].fromSchema(schema)\r\n field.required = modelSchema.required.includes(key)\r\n field.name = key\r\n return field\r\n }\r\n }\r\n })\r\n}\r\n"],"file":"index.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/link.js b/packages/common/lib/schema/types/link.js index 85a4626523..cc7013df2b 100644 --- a/packages/common/lib/schema/types/link.js +++ b/packages/common/lib/schema/types/link.js @@ -1,42 +1,26 @@ -"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _fp = require("lodash/fp"); -var _typeHelpers = require("./typeHelpers"); -var _index = require("../../common/index.js"); +"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _default2 = { + isType: function isType(schema) {return schema.type === "object" && schema.properties.modelId;}, + + fromSchema: function fromSchema(schema) {return { + type: "link", + modelId: schema.properties.modelId["const"], + viewId: schema.properties.viewId["const"], + "default": schema["default"] };}, + toSchema: function toSchema(field) {return { + type: "object", + properties: { + _id: { type: "string" }, + viewId: field.viewId ? { "const": field.viewId } : undefined, + modelId: field.modelId ? { "const": field.modelId } : undefined }, + + required: ["_id"], + "default": { _id: "" } };}, - -var linkNothing = function linkNothing() {return "";}; - -var linkFunctions = (0, _typeHelpers.typeFunctions)({ - "default": linkNothing }); - - -var linkTryParse = function linkTryParse(v) {return ( - (0, _index.switchCase)( - [_fp.isString, function (s) {return (0, _typeHelpers.parsedSuccess)(s);}], - [_fp.isNull, function () {return (0, _typeHelpers.parsedSuccess)(linkNothing());}], - [_fp.isUndefined, function () {return (0, _typeHelpers.parsedSuccess)(linkNothing());}], - [_index.defaultCase, function (s) {return (0, _typeHelpers.parsedSuccess)(s.toString());}])( - v));}; - -var options = { - modelId: { - defaultValue: "", - isValid: _index.isNonEmptyString, - requirementDescription: "must choose a model", - parse: function parse(s) {return s;} } }; - - - -var typeConstraints = [];var _default = - -(0, _typeHelpers.getDefaultExport)( -"link", -linkTryParse, -linkFunctions, -options, -typeConstraints, -"abcd1234", -JSON.stringify);exports["default"] = _default; + "default": function _default() {return { + type: "link", + modelId: null, + viewId: null };} };exports["default"] = _default2; //# sourceMappingURL=link.js.map \ No newline at end of file diff --git a/packages/common/lib/schema/types/link.js.map b/packages/common/lib/schema/types/link.js.map index 8bd94f4726..b9930a2c18 100644 --- a/packages/common/lib/schema/types/link.js.map +++ b/packages/common/lib/schema/types/link.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/schema/types/link.js"],"names":["linkNothing","linkFunctions","linkTryParse","v","isString","s","isNull","isUndefined","defaultCase","toString","options","modelId","defaultValue","isValid","isNonEmptyString","requirementDescription","parse","typeConstraints","JSON","stringify"],"mappings":"uGAAA;AACA;AACA;;;;;;AAMA,IAAMA,WAAW,GAAG,SAAdA,WAAc,WAAM,EAAN,EAApB;;AAEA,IAAMC,aAAa,GAAG,gCAAc;AAClC,aAASD,WADyB,EAAd,CAAtB;;;AAIA,IAAME,YAAY,GAAG,SAAfA,YAAe,CAAAC,CAAC;AACpB;AACE,KAACC,YAAD,EAAW,UAAAC,CAAC,UAAI,gCAAcA,CAAd,CAAJ,EAAZ,CADF;AAEE,KAACC,UAAD,EAAS,oBAAM,gCAAcN,WAAW,EAAzB,CAAN,EAAT,CAFF;AAGE,KAACO,eAAD,EAAc,oBAAM,gCAAcP,WAAW,EAAzB,CAAN,EAAd,CAHF;AAIE,KAACQ,kBAAD,EAAc,UAAAH,CAAC,UAAI,gCAAcA,CAAC,CAACI,QAAF,EAAd,CAAJ,EAAf,CAJF;AAKEN,IAAAA,CALF,CADoB,GAAtB;;AAQA,IAAMO,OAAO,GAAG;AACdC,EAAAA,OAAO,EAAE;AACPC,IAAAA,YAAY,EAAE,EADP;AAEPC,IAAAA,OAAO,EAAEC,uBAFF;AAGPC,IAAAA,sBAAsB,EAAE,qBAHjB;AAIPC,IAAAA,KAAK,EAAE,eAAAX,CAAC,UAAIA,CAAJ,EAJD,EADK,EAAhB;;;;AASA,IAAMY,eAAe,GAAG,EAAxB,C;;AAEe;AACb,MADa;AAEbf,YAFa;AAGbD,aAHa;AAIbS,OAJa;AAKbO,eALa;AAMb,UANa;AAObC,IAAI,CAACC,SAPQ,C","sourcesContent":["import { isString, isUndefined, isNull } from \"lodash/fp\"\nimport { typeFunctions, parsedSuccess, getDefaultExport } from \"./typeHelpers\"\nimport {\n switchCase,\n defaultCase,\n isNonEmptyString,\n} from \"../../common/index.js\"\n\nconst linkNothing = () => \"\"\n\nconst linkFunctions = typeFunctions({\n default: linkNothing,\n})\n\nconst linkTryParse = v =>\n switchCase(\n [isString, s => parsedSuccess(s)],\n [isNull, () => parsedSuccess(linkNothing())],\n [isUndefined, () => parsedSuccess(linkNothing())],\n [defaultCase, s => parsedSuccess(s.toString())]\n )(v)\n\nconst options = {\n modelId: {\n defaultValue: \"\",\n isValid: isNonEmptyString,\n requirementDescription: \"must choose a model\",\n parse: s => s,\n },\n}\n\nconst typeConstraints = []\n\nexport default getDefaultExport(\n \"link\",\n linkTryParse,\n linkFunctions,\n options,\n typeConstraints,\n \"abcd1234\",\n JSON.stringify\n)\n"],"file":"link.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/schema/types/link.js"],"names":["isType","schema","type","properties","modelId","fromSchema","viewId","toSchema","field","_id","undefined","required"],"mappings":"uHAAe;AACbA,EAAAA,MAAM,EAAE,gBAAAC,MAAM,UAAIA,MAAM,CAACC,IAAP,KAAgB,QAAhB,IAA4BD,MAAM,CAACE,UAAP,CAAkBC,OAAlD,EADD;;AAGbC,EAAAA,UAAU,EAAE,oBAAAJ,MAAM,UAAK;AACrBC,MAAAA,IAAI,EAAE,MADe;AAErBE,MAAAA,OAAO,EAAEH,MAAM,CAACE,UAAP,CAAkBC,OAAlB,SAFY;AAGrBE,MAAAA,MAAM,EAAEL,MAAM,CAACE,UAAP,CAAkBG,MAAlB,SAHa;AAIrB,iBAASL,MAAM,WAJM,EAAL,EAHL;;;AAUbM,EAAAA,QAAQ,EAAE,kBAAAC,KAAK,UAAK;AAClBN,MAAAA,IAAI,EAAE,QADY;AAElBC,MAAAA,UAAU,EAAE;AACVM,QAAAA,GAAG,EAAE,EAAEP,IAAI,EAAE,QAAR,EADK;AAEVI,QAAAA,MAAM,EAAEE,KAAK,CAACF,MAAN,GAAe,EAAE,SAAOE,KAAK,CAACF,MAAf,EAAf,GAAyCI,SAFvC;AAGVN,QAAAA,OAAO,EAAEI,KAAK,CAACJ,OAAN,GAAgB,EAAE,SAAOI,KAAK,CAACJ,OAAf,EAAhB,GAA2CM,SAH1C,EAFM;;AAOlBC,MAAAA,QAAQ,EAAE,CAAC,KAAD,CAPQ;AAQlB,iBAAS,EAAEF,GAAG,EAAE,EAAP,EARS,EAAL,EAVF;;;AAqBb,aAAS,4BAAO;AACdP,MAAAA,IAAI,EAAE,MADQ;AAEdE,MAAAA,OAAO,EAAE,IAFK;AAGdE,MAAAA,MAAM,EAAE,IAHM,EAAP,EArBI,E","sourcesContent":["export default {\r\n isType: schema => schema.type === \"object\" && schema.properties.modelId,\r\n\r\n fromSchema: schema => ({\r\n type: \"link\",\r\n modelId: schema.properties.modelId.const,\r\n viewId: schema.properties.viewId.const,\r\n default: schema.default,\r\n }),\r\n\r\n toSchema: field => ({\r\n type: \"object\",\r\n properties: {\r\n _id: { type: \"string\" },\r\n viewId: field.viewId ? { const: field.viewId } : undefined,\r\n modelId: field.modelId ? { const: field.modelId } : undefined,\r\n },\r\n required: [\"_id\"],\r\n default: { _id: \"\" },\r\n }),\r\n\r\n default: () => ({\r\n type: \"link\",\r\n modelId: null,\r\n viewId: null,\r\n }),\r\n}\r\n"],"file":"link.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/number.js b/packages/common/lib/schema/types/number.js index 2ce66eb376..ef20ee930e 100644 --- a/packages/common/lib/schema/types/number.js +++ b/packages/common/lib/schema/types/number.js @@ -1,94 +1,14 @@ -"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _fp = require("lodash/fp"); -var _typeHelpers = require("./typeHelpers"); +"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _default2 = { + isType: function isType(schema) {return schema.type === "number";}, + fromSchema: function fromSchema(schema) {return schema;}, + toSchema: function toSchema(field) {return { + type: "number", + maximum: field.maximum, + minimum: field.minimum, + "default": undefined };}, - - - - - -var _index = require("../../common/index.js"); - - - - - - -var numberFunctions = (0, _typeHelpers.typeFunctions)({ - "default": (0, _fp.constant)(null) }); - - -var parseStringtoNumberOrNull = function parseStringtoNumberOrNull(s) { - var num = Number(s); - return isNaN(num) ? (0, _typeHelpers.parsedFailed)(s) : (0, _typeHelpers.parsedSuccess)(num); -}; - -var numberTryParse = (0, _index.switchCase)( -[_fp.isNumber, _typeHelpers.parsedSuccess], -[_fp.isString, parseStringtoNumberOrNull], -[_fp.isNull, _typeHelpers.parsedSuccess], -[_index.defaultCase, _typeHelpers.parsedFailed]); - - -var options = { - maxValue: { - defaultValue: Number.MAX_SAFE_INTEGER, - isValid: _index.isSafeInteger, - requirementDescription: "must be a valid integer", - parse: _index.toNumberOrNull }, - - minValue: { - defaultValue: 0 - Number.MAX_SAFE_INTEGER, - isValid: _index.isSafeInteger, - requirementDescription: "must be a valid integer", - parse: _index.toNumberOrNull }, - - decimalPlaces: { - defaultValue: 0, - isValid: function isValid(n) {return (0, _index.isSafeInteger)(n) && n >= 0;}, - requirementDescription: "must be a positive integer", - parse: _index.toNumberOrNull } }; - - - -var getDecimalPlaces = function getDecimalPlaces(val) { - var splitDecimal = val.toString().split("."); - if (splitDecimal.length === 1) return 0; - return splitDecimal[1].length; -}; - -var typeConstraints = [ -(0, _typeHelpers.makerule)( -function (val, opts) {return ( - val === null || opts.minValue === null || val >= opts.minValue);}, -function (val, opts) {return "value (".concat( - val.toString(), ") must be greater than or equal to ").concat( - opts.minValue);}), - - -(0, _typeHelpers.makerule)( -function (val, opts) {return ( - val === null || opts.maxValue === null || val <= opts.maxValue);}, -function (val, opts) {return "value (".concat( - val.toString(), ") must be less than or equal to ").concat( - opts.minValue, " options");}), - - -(0, _typeHelpers.makerule)( -function (val, opts) {return ( - val === null || opts.decimalPlaces >= getDecimalPlaces(val));}, -function (val, opts) {return "value (".concat( - val.toString(), ") must have ").concat( - opts.decimalPlaces, " decimal places or less");})];var _default = - - - - -(0, _typeHelpers.getDefaultExport)( -"number", -numberTryParse, -numberFunctions, -options, -typeConstraints, -1, -function (num) {return num.toString();});exports["default"] = _default; + "default": function _default() {return { + type: "number", + maximum: null, + minimum: null };} };exports["default"] = _default2; //# sourceMappingURL=number.js.map \ No newline at end of file diff --git a/packages/common/lib/schema/types/number.js.map b/packages/common/lib/schema/types/number.js.map index 9d2b7cf610..1f8afe4adf 100644 --- a/packages/common/lib/schema/types/number.js.map +++ b/packages/common/lib/schema/types/number.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/schema/types/number.js"],"names":["numberFunctions","parseStringtoNumberOrNull","s","num","Number","isNaN","numberTryParse","isNumber","parsedSuccess","isString","isNull","defaultCase","parsedFailed","options","maxValue","defaultValue","MAX_SAFE_INTEGER","isValid","isSafeInteger","requirementDescription","parse","toNumberOrNull","minValue","decimalPlaces","n","getDecimalPlaces","val","splitDecimal","toString","split","length","typeConstraints","opts"],"mappings":"uGAAA;AACA;;;;;;;AAOA;;;;;;;AAOA,IAAMA,eAAe,GAAG,gCAAc;AACpC,aAAS,kBAAS,IAAT,CAD2B,EAAd,CAAxB;;;AAIA,IAAMC,yBAAyB,GAAG,SAA5BA,yBAA4B,CAAAC,CAAC,EAAI;AACrC,MAAMC,GAAG,GAAGC,MAAM,CAACF,CAAD,CAAlB;AACA,SAAOG,KAAK,CAACF,GAAD,CAAL,GAAa,+BAAaD,CAAb,CAAb,GAA+B,gCAAcC,GAAd,CAAtC;AACD,CAHD;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AkB,IAAlC,IAA0CI,GAAG,IAAIM,IAAI,CAACV,QADxD,GADF;AAGE,UAACI,GAAD,EAAMM,IAAN;AACYN,EAAAA,GAAG,CAACE,QAAJ,EADZ;AAEII,EAAAA,IAAI,CAACV,QAFT,GAHF,CADsB;;;AAStB;AACE,UAACI,GAAD,EAAMM,IAAN;AACEN,IAAAA,GAAG,KAAK,IAAR,IAAgBM,IAAI,CAAClB,QAAL,KAAkB,IAAlC,IAA0CY,GAAG,IAAIM,IAAI,CAAClB,QADxD,GADF;AAGE,UAACY,GAAD,EAAMM,IAAN;AACYN,EAAAA,GAAG,CAACE,QAAJ,EADZ;AAEII,EAAAA,IAAI,CAACV,QAFT,eAHF,CATsB;;;AAiBtB;AACE,UAACI,GAAD,EAAMM,IAAN;AACEN,IAAAA,GAAG,KAAK,IAAR,IAAgBM,IAAI,CAACT,aAAL,IAAsBE,gBAAgB,CAACC,GAAD,CADxD,GADF;AAGE,UAACA,GAAD,EAAMM,IAAN;AACYN,EAAAA,GAAG,CAACE,QAAJ,EADZ;AAEII,EAAAA,IAAI,CAACT,aAFT,8BAHF,CAjBsB,CAAxB,C;;;;;AA2Be;AACb,QADa;AAEbjB,cAFa;AAGbN,eAHa;AAIba,OAJa;AAKbkB,eALa;AAMb,CANa;AAOb,UAAA5B,GAAG,UAAIA,GAAG,CAACyB,QAAJ,EAAJ,EAPU,C","sourcesContent":["import { constant, isNumber, isString, isNull } from \"lodash/fp\"\nimport {\n makerule,\n typeFunctions,\n parsedFailed,\n parsedSuccess,\n getDefaultExport,\n} from \"./typeHelpers\"\nimport {\n switchCase,\n defaultCase,\n toNumberOrNull,\n isSafeInteger,\n} from \"../../common/index.js\"\n\nconst numberFunctions = typeFunctions({\n default: constant(null),\n})\n\nconst parseStringtoNumberOrNull = s => {\n const num = Number(s)\n return isNaN(num) ? parsedFailed(s) : parsedSuccess(num)\n}\n\nconst numberTryParse = switchCase(\n [isNumber, parsedSuccess],\n [isString, parseStringtoNumberOrNull],\n [isNull, parsedSuccess],\n [defaultCase, parsedFailed]\n)\n\nconst options = {\n maxValue: {\n defaultValue: Number.MAX_SAFE_INTEGER,\n isValid: isSafeInteger,\n requirementDescription: \"must be a valid integer\",\n parse: toNumberOrNull,\n },\n minValue: {\n defaultValue: 0 - Number.MAX_SAFE_INTEGER,\n isValid: isSafeInteger,\n requirementDescription: \"must be a valid integer\",\n parse: toNumberOrNull,\n },\n decimalPlaces: {\n defaultValue: 0,\n isValid: n => isSafeInteger(n) && n >= 0,\n requirementDescription: \"must be a positive integer\",\n parse: toNumberOrNull,\n },\n}\n\nconst getDecimalPlaces = val => {\n const splitDecimal = val.toString().split(\".\")\n if (splitDecimal.length === 1) return 0\n return splitDecimal[1].length\n}\n\nconst typeConstraints = [\n makerule(\n (val, opts) =>\n val === null || opts.minValue === null || val >= opts.minValue,\n (val, opts) =>\n `value (${val.toString()}) must be greater than or equal to ${\n opts.minValue\n }`\n ),\n makerule(\n (val, opts) =>\n val === null || opts.maxValue === null || val <= opts.maxValue,\n (val, opts) =>\n `value (${val.toString()}) must be less than or equal to ${\n opts.minValue\n } options`\n ),\n makerule(\n (val, opts) =>\n val === null || opts.decimalPlaces >= getDecimalPlaces(val),\n (val, opts) =>\n `value (${val.toString()}) must have ${\n opts.decimalPlaces\n } decimal places or less`\n ),\n]\n\nexport default getDefaultExport(\n \"number\",\n numberTryParse,\n numberFunctions,\n options,\n typeConstraints,\n 1,\n num => num.toString()\n)\n"],"file":"number.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/schema/types/number.js"],"names":["isType","schema","type","fromSchema","toSchema","field","maximum","minimum","undefined"],"mappings":"uHAAe;AACbA,EAAAA,MAAM,EAAE,gBAAAC,MAAM,UAAIA,MAAM,CAACC,IAAP,KAAgB,QAApB,EADD;AAEbC,EAAAA,UAAU,EAAE,oBAAAF,MAAM,UAAIA,MAAJ,EAFL;AAGbG,EAAAA,QAAQ,EAAE,kBAAAC,KAAK,UAAK;AAClBH,MAAAA,IAAI,EAAE,QADY;AAElBI,MAAAA,OAAO,EAAED,KAAK,CAACC,OAFG;AAGlBC,MAAAA,OAAO,EAAEF,KAAK,CAACE,OAHG;AAIlB,iBAASC,SAJS,EAAL,EAHF;;AASb,aAAS,4BAAO;AACdN,MAAAA,IAAI,EAAE,QADQ;AAEdI,MAAAA,OAAO,EAAE,IAFK;AAGdC,MAAAA,OAAO,EAAE,IAHK,EAAP,EATI,E","sourcesContent":["export default {\r\n isType: schema => schema.type === \"number\",\r\n fromSchema: schema => schema,\r\n toSchema: field => ({\r\n type: \"number\",\r\n maximum: field.maximum,\r\n minimum: field.minimum,\r\n default: undefined,\r\n }),\r\n default: () => ({\r\n type: \"number\",\r\n maximum: null,\r\n minimum: null,\r\n }),\r\n}\r\n"],"file":"number.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/object.js.map b/packages/common/lib/schema/types/object.js.map index 3ff33f277a..17b00f7537 100644 --- a/packages/common/lib/schema/types/object.js.map +++ b/packages/common/lib/schema/types/object.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/schema/types/object.js"],"names":["objectFunctions","definition","allTypes","initialise","defClone","k","getNew","parseObject","record","type","safeParseValue","objectTryParse","isNull","parsedSuccess","isObject","defaultCase","parsedFailed","typeName","defaultOptions","typeConstraints","sampleValue","JSON","stringify"],"mappings":"uGAAA;AACA;;;;;;AAMA;;AAEA,IAAMA,eAAe,GAAG,SAAlBA,eAAkB,CAACC,UAAD,EAAaC,QAAb;AACtB,oCAAc;AACZ,iBAAS,sBAAS,IAAT,CADG;AAEZC,MAAAA,UAAU,EAAE;AACV,wBAAE,kBAAKF,UAAL,CAAF,EAAoB;AAClB,2BAAI,YAAM;AACR,gBAAMG,QAAQ,GAAG,mBAAMH,UAAN,CAAjB;AACA,iBAAK,IAAMI,CAAX,IAAgBD,QAAhB,EAA0B;AACxBA,cAAAA,QAAQ,CAACC,CAAD,CAAR,GAAcH,QAAQ,CAACG,CAAD,CAAR,CAAYC,MAAZ,EAAd;AACD;AACD,mBAAOF,QAAP;AACD,WAND,CADkB,CAApB,CADU,GAFA,EAAd,CADsB,GAAxB;;;;AAeA,IAAMG,WAAW,GAAG,SAAdA,WAAc,CAACN,UAAD,EAAaC,QAAb,UAA0B,UAAAM,MAAM,EAAI;AACtD,QAAMJ,QAAQ,GAAG,mBAAMH,UAAN,CAAjB;AACA,SAAK,IAAMI,CAAX,IAAgBD,QAAhB,EAA0B;AACxB,UAAMK,IAAI,GAAGP,QAAQ,CAACE,QAAQ,CAACC,CAAD,CAAT,CAArB;AACAD,MAAAA,QAAQ,CAACC,CAAD,CAAR,GAAc,iBAAIG,MAAJ,EAAYH,CAAZ;AACVI,MAAAA,IAAI,CAACC,cAAL,CAAoBF,MAAM,CAACH,CAAD,CAA1B,CADU;AAEVI,MAAAA,IAAI,CAACH,MAAL,EAFJ;AAGD;AACD,WAAO,gCAAcF,QAAd,CAAP;AACD,GATmB,EAApB;;AAWA,IAAMO,cAAc,GAAG,SAAjBA,cAAiB,CAACV,UAAD,EAAaC,QAAb;AACrB;AACE,KAACU,cAAD,EAASC,0BAAT,CADF;AAEE,KAACC,gBAAD,EAAWP,WAAW,CAACN,UAAD,EAAaC,QAAb,CAAtB,CAFF;AAGE,KAACa,kBAAD,EAAcC,yBAAd,CAHF,CADqB,GAAvB,C;;;AAOe;AACbC,QADa;AAEbhB,UAFa;AAGbC,QAHa;AAIbgB,cAJa;AAKbC,eALa;AAMbC,WANa;;AAQb;AACEH,IAAAA,QADF;AAEEN,IAAAA,cAAc,CAACV,UAAD,EAAaC,QAAb,CAFhB;AAGEF,IAAAA,eAAe,CAACC,UAAD,EAAaC,QAAb,CAHjB;AAIEgB,IAAAA,cAJF;AAKEC,IAAAA,eALF;AAMEC,IAAAA,WANF;AAOEC,IAAAA,IAAI,CAACC,SAPP,CARa,G","sourcesContent":["import { keys, isObject, has, clone, map, isNull, constant } from \"lodash\"\nimport {\n typeFunctions,\n parsedFailed,\n parsedSuccess,\n getDefaultExport,\n} from \"./typeHelpers\"\nimport { switchCase, defaultCase, $ } from \"../../common/index.js\"\n\nconst objectFunctions = (definition, allTypes) =>\n typeFunctions({\n default: constant(null),\n initialise: () =>\n $(keys(definition), [\n map(() => {\n const defClone = clone(definition)\n for (const k in defClone) {\n defClone[k] = allTypes[k].getNew()\n }\n return defClone\n }),\n ]),\n })\n\nconst parseObject = (definition, allTypes) => record => {\n const defClone = clone(definition)\n for (const k in defClone) {\n const type = allTypes[defClone[k]]\n defClone[k] = has(record, k)\n ? type.safeParseValue(record[k])\n : type.getNew()\n }\n return parsedSuccess(defClone)\n}\n\nconst objectTryParse = (definition, allTypes) =>\n switchCase(\n [isNull, parsedSuccess],\n [isObject, parseObject(definition, allTypes)],\n [defaultCase, parsedFailed]\n )\n\nexport default (\n typeName,\n definition,\n allTypes,\n defaultOptions,\n typeConstraints,\n sampleValue\n) =>\n getDefaultExport(\n typeName,\n objectTryParse(definition, allTypes),\n objectFunctions(definition, allTypes),\n defaultOptions,\n typeConstraints,\n sampleValue,\n JSON.stringify\n )\n"],"file":"object.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/schema/types/object.js"],"names":["objectFunctions","definition","allTypes","initialise","defClone","k","getNew","parseObject","record","type","safeParseValue","objectTryParse","isNull","parsedSuccess","isObject","defaultCase","parsedFailed","typeName","defaultOptions","typeConstraints","sampleValue","JSON","stringify"],"mappings":"uGAAA;AACA;;;;;;AAMA;;AAEA,IAAMA,eAAe,GAAG,SAAlBA,eAAkB,CAACC,UAAD,EAAaC,QAAb;AACtB,oCAAc;AACZ,iBAAS,sBAAS,IAAT,CADG;AAEZC,MAAAA,UAAU,EAAE;AACV,wBAAE,kBAAKF,UAAL,CAAF,EAAoB;AAClB,2BAAI,YAAM;AACR,gBAAMG,QAAQ,GAAG,mBAAMH,UAAN,CAAjB;AACA,iBAAK,IAAMI,CAAX,IAAgBD,QAAhB,EAA0B;AACxBA,cAAAA,QAAQ,CAACC,CAAD,CAAR,GAAcH,QAAQ,CAACG,CAAD,CAAR,CAAYC,MAAZ,EAAd;AACD;AACD,mBAAOF,QAAP;AACD,WAND,CADkB,CAApB,CADU,GAFA,EAAd,CADsB,GAAxB;;;;AAeA,IAAMG,WAAW,GAAG,SAAdA,WAAc,CAACN,UAAD,EAAaC,QAAb,UAA0B,UAAAM,MAAM,EAAI;AACtD,QAAMJ,QAAQ,GAAG,mBAAMH,UAAN,CAAjB;AACA,SAAK,IAAMI,CAAX,IAAgBD,QAAhB,EAA0B;AACxB,UAAMK,IAAI,GAAGP,QAAQ,CAACE,QAAQ,CAACC,CAAD,CAAT,CAArB;AACAD,MAAAA,QAAQ,CAACC,CAAD,CAAR,GAAc,iBAAIG,MAAJ,EAAYH,CAAZ;AACVI,MAAAA,IAAI,CAACC,cAAL,CAAoBF,MAAM,CAACH,CAAD,CAA1B,CADU;AAEVI,MAAAA,IAAI,CAACH,MAAL,EAFJ;AAGD;AACD,WAAO,gCAAcF,QAAd,CAAP;AACD,GATmB,EAApB;;AAWA,IAAMO,cAAc,GAAG,SAAjBA,cAAiB,CAACV,UAAD,EAAaC,QAAb;AACrB;AACE,KAACU,cAAD,EAASC,0BAAT,CADF;AAEE,KAACC,gBAAD,EAAWP,WAAW,CAACN,UAAD,EAAaC,QAAb,CAAtB,CAFF;AAGE,KAACa,kBAAD,EAAcC,yBAAd,CAHF,CADqB,GAAvB,C;;;AAOe;AACbC,QADa;AAEbhB,UAFa;AAGbC,QAHa;AAIbgB,cAJa;AAKbC,eALa;AAMbC,WANa;;AAQb;AACEH,IAAAA,QADF;AAEEN,IAAAA,cAAc,CAACV,UAAD,EAAaC,QAAb,CAFhB;AAGEF,IAAAA,eAAe,CAACC,UAAD,EAAaC,QAAb,CAHjB;AAIEgB,IAAAA,cAJF;AAKEC,IAAAA,eALF;AAMEC,IAAAA,WANF;AAOEC,IAAAA,IAAI,CAACC,SAPP,CARa,G","sourcesContent":["import { keys, isObject, has, clone, map, isNull, constant } from \"lodash\"\r\nimport {\r\n typeFunctions,\r\n parsedFailed,\r\n parsedSuccess,\r\n getDefaultExport,\r\n} from \"./typeHelpers\"\r\nimport { switchCase, defaultCase, $ } from \"../../common/index.js\"\r\n\r\nconst objectFunctions = (definition, allTypes) =>\r\n typeFunctions({\r\n default: constant(null),\r\n initialise: () =>\r\n $(keys(definition), [\r\n map(() => {\r\n const defClone = clone(definition)\r\n for (const k in defClone) {\r\n defClone[k] = allTypes[k].getNew()\r\n }\r\n return defClone\r\n }),\r\n ]),\r\n })\r\n\r\nconst parseObject = (definition, allTypes) => record => {\r\n const defClone = clone(definition)\r\n for (const k in defClone) {\r\n const type = allTypes[defClone[k]]\r\n defClone[k] = has(record, k)\r\n ? type.safeParseValue(record[k])\r\n : type.getNew()\r\n }\r\n return parsedSuccess(defClone)\r\n}\r\n\r\nconst objectTryParse = (definition, allTypes) =>\r\n switchCase(\r\n [isNull, parsedSuccess],\r\n [isObject, parseObject(definition, allTypes)],\r\n [defaultCase, parsedFailed]\r\n )\r\n\r\nexport default (\r\n typeName,\r\n definition,\r\n allTypes,\r\n defaultOptions,\r\n typeConstraints,\r\n sampleValue\r\n) =>\r\n getDefaultExport(\r\n typeName,\r\n objectTryParse(definition, allTypes),\r\n objectFunctions(definition, allTypes),\r\n defaultOptions,\r\n typeConstraints,\r\n sampleValue,\r\n JSON.stringify\r\n )\r\n"],"file":"object.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/string.js.map b/packages/common/lib/schema/types/string.js.map index 12eb59c17c..aa3642239b 100644 --- a/packages/common/lib/schema/types/string.js.map +++ b/packages/common/lib/schema/types/string.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/schema/types/string.js"],"names":["stringFunctions","stringTryParse","isString","parsedSuccess","isNull","defaultCase","v","toString","options","maxLength","defaultValue","isValid","n","requirementDescription","parse","toNumberOrNull","values","length","s","allowDeclaredValuesOnly","isBoolean","toBoolOrNull","typeConstraints","val","opts","str"],"mappings":"uGAAA;AACA;;;;;;AAMA;;;;;;;;;AASA,IAAMA,eAAe,GAAG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cO,IAAI,CAACf,SADhE,GADF;AAGE,UAACc,GAAD,EAAMC,IAAN,oDAAkDA,IAAI,CAACf,SAAvD,GAHF,CADsB;;AAMtB;AACE,UAACc,GAAD,EAAMC,IAAN;AACED,IAAAA,GAAG,KAAK,IAAR;AACAC,IAAAA,IAAI,CAACL,uBAAL,KAAiC,KADjC;AAEA,sBAASI,GAAT,EAAcC,IAAI,CAACR,MAAnB,CAHF,GADF;AAKE,UAAAO,GAAG,sBAAQA,GAAR,sDALL,CANsB,CAAxB,C;;;;AAee;AACb,QADa;AAEbtB,cAFa;AAGbD,eAHa;AAIbQ,OAJa;AAKbc,eALa;AAMb,OANa;AAOb,UAAAG,GAAG,UAAIA,GAAJ,EAPU,C","sourcesContent":["import { constant, isString, isNull, includes, isBoolean } from \"lodash/fp\"\nimport {\n typeFunctions,\n makerule,\n parsedSuccess,\n getDefaultExport,\n} from \"./typeHelpers\"\nimport {\n switchCase,\n defaultCase,\n toBoolOrNull,\n toNumberOrNull,\n isSafeInteger,\n isArrayOfString,\n} from \"../../common/index.js\"\n\nconst stringFunctions = typeFunctions({\n default: constant(null),\n})\n\nconst stringTryParse = switchCase(\n [isString, parsedSuccess],\n [isNull, parsedSuccess],\n [defaultCase, v => parsedSuccess(v.toString())]\n)\n\nconst options = {\n maxLength: {\n defaultValue: null,\n isValid: n => n === null || (isSafeInteger(n) && n > 0),\n requirementDescription:\n \"max length must be null (no limit) or a greater than zero integer\",\n parse: toNumberOrNull,\n },\n values: {\n defaultValue: null,\n isValid: v =>\n v === null || (isArrayOfString(v) && v.length > 0 && v.length < 10000),\n requirementDescription:\n \"'values' must be null (no values) or an array of at least one string\",\n parse: s => s,\n },\n allowDeclaredValuesOnly: {\n defaultValue: false,\n isValid: isBoolean,\n requirementDescription: \"allowDeclaredValuesOnly must be true or false\",\n parse: toBoolOrNull,\n },\n}\n\nconst typeConstraints = [\n makerule(\n (val, opts) =>\n val === null || opts.maxLength === null || val.length <= opts.maxLength,\n (val, opts) => `value exceeds maximum length of ${opts.maxLength}`\n ),\n makerule(\n (val, opts) =>\n val === null ||\n opts.allowDeclaredValuesOnly === false ||\n includes(val)(opts.values),\n val => `\"${val}\" does not exist in the list of allowed values`\n ),\n]\n\nexport default getDefaultExport(\n \"string\",\n stringTryParse,\n stringFunctions,\n options,\n typeConstraints,\n \"abcde\",\n str => str\n)\n"],"file":"string.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/schema/types/string.js"],"names":["stringFunctions","stringTryParse","isString","parsedSuccess","isNull","defaultCase","v","toString","options","maxLength","defaultValue","isValid","n","requirementDescription","parse","toNumberOrNull","values","length","s","allowDeclaredValuesOnly","isBoolean","toBoolOrNull","typeConstraints","val","opts","str"],"mappings":"uGAAA;AACA;;;;;;AAMA;;;;;;;;;AASA,IAAMA,eAAe,GAAG,gCAAc;AACpC,aAAS,kBAAS,IAAT,CAD2B,EAAd,CAAxB;;;AAIA,IAAMC,cAAc,GAAG;AACrB,CAACC,YAAD,EAAWC,0BAAX,CADqB;AAErB,CAACC,UAAD,EAASD,0BAAT,CAFqB;AAGrB,CAACE,kBAAD,EAAc,UAAAC,CAAC,UAAI,gCAAcA,CAAC,CAACC,QAAF,EAAd,CAAJ,EAAf,CAHqB,CAAvB;;;AAMA,IAAMC,OAAO,GAAG;AACdC,EAAAA,SAAS,EAAE;AACTC,IAAAA,YAAY,EAAE,IADL;AAETC,IAAAA,OAAO,EAAE,iBAAAC,CAAC,UAAIA,CAAC,KAAK,IAAN,IAAe,0BAAcA,CAAd,KAAoBA,CAAC,GAAG,CAA3C,EAFD;AAGTC,IAAAA,sBAAsB;AACpB,uEAJO;AAKTC,IAAAA,KAAK,EAAEC,qBALE,EADG;;AAQdC,EAAAA,MAAM,EAAE;AACNN,IAAAA,YAAY,EAAE,IADR;AAENC,IAAAA,OAAO,EAAE,iBAAAL,CAAC;AACRA,QAAAA,CAAC,KAAK,IAAN,IAAe,4BAAgBA,CAAhB,KAAsBA,CAAC,CAACW,MAAF,GAAW,CAAjC,IAAsCX,CAAC,CAACW,MAAF,GAAW,KADxD,GAFJ;AAINJ,IAAAA,sBAAsB;AACpB,0EALI;AAMNC,IAAAA,KAAK,EAAE,eAAAI,CAAC,UAAIA,CAAJ,EANF,EARM;;AAgBdC,EAAAA,uBAAuB,EAAE;AACvBT,IAAAA,YAAY,EAAE,KADS;AAEvBC,IAAAA,OAAO,EAAES,aAFc;AAGvBP,IAAAA,sBAAsB,EAAE,+CAHD;AAIvBC,IAAAA,KAAK,EAAEO,mBAJgB,EAhBX,EAAhB;;;;AAwBA,IAAMC,eAAe,GAAG;AACtB;AACE,UAACC,GAAD,EAAMC,IAAN;AACED,IAAAA,GAAG,KAAK,IAAR,IAAgBC,IAAI,CAACf,SAAL,KAAmB,IAAnC,IAA2Cc,GAAG,CAACN,MAAJ,IAAcO,IAAI,CAACf,SADhE,GADF;AAGE,UAACc,GAAD,EAAMC,IAAN,oDAAkDA,IAAI,CAACf,SAAvD,GAHF,CADsB;;AAMtB;AACE,UAACc,GAAD,EAAMC,IAAN;AACED,IAAAA,GAAG,KAAK,IAAR;AACAC,IAAAA,IAAI,CAACL,uBAAL,KAAiC,KADjC;AAEA,sBAASI,GAAT,EAAcC,IAAI,CAACR,MAAnB,CAHF,GADF;AAKE,UAAAO,GAAG,sBAAQA,GAAR,sDALL,CANsB,CAAxB,C;;;;AAee;AACb,QADa;AAEbtB,cAFa;AAGbD,eAHa;AAIbQ,OAJa;AAKbc,eALa;AAMb,OANa;AAOb,UAAAG,GAAG,UAAIA,GAAJ,EAPU,C","sourcesContent":["import { constant, isString, isNull, includes, isBoolean } from \"lodash/fp\"\r\nimport {\r\n typeFunctions,\r\n makerule,\r\n parsedSuccess,\r\n getDefaultExport,\r\n} from \"./typeHelpers\"\r\nimport {\r\n switchCase,\r\n defaultCase,\r\n toBoolOrNull,\r\n toNumberOrNull,\r\n isSafeInteger,\r\n isArrayOfString,\r\n} from \"../../common/index.js\"\r\n\r\nconst stringFunctions = typeFunctions({\r\n default: constant(null),\r\n})\r\n\r\nconst stringTryParse = switchCase(\r\n [isString, parsedSuccess],\r\n [isNull, parsedSuccess],\r\n [defaultCase, v => parsedSuccess(v.toString())]\r\n)\r\n\r\nconst options = {\r\n maxLength: {\r\n defaultValue: null,\r\n isValid: n => n === null || (isSafeInteger(n) && n > 0),\r\n requirementDescription:\r\n \"max length must be null (no limit) or a greater than zero integer\",\r\n parse: toNumberOrNull,\r\n },\r\n values: {\r\n defaultValue: null,\r\n isValid: v =>\r\n v === null || (isArrayOfString(v) && v.length > 0 && v.length < 10000),\r\n requirementDescription:\r\n \"'values' must be null (no values) or an array of at least one string\",\r\n parse: s => s,\r\n },\r\n allowDeclaredValuesOnly: {\r\n defaultValue: false,\r\n isValid: isBoolean,\r\n requirementDescription: \"allowDeclaredValuesOnly must be true or false\",\r\n parse: toBoolOrNull,\r\n },\r\n}\r\n\r\nconst typeConstraints = [\r\n makerule(\r\n (val, opts) =>\r\n val === null || opts.maxLength === null || val.length <= opts.maxLength,\r\n (val, opts) => `value exceeds maximum length of ${opts.maxLength}`\r\n ),\r\n makerule(\r\n (val, opts) =>\r\n val === null ||\r\n opts.allowDeclaredValuesOnly === false ||\r\n includes(val)(opts.values),\r\n val => `\"${val}\" does not exist in the list of allowed values`\r\n ),\r\n]\r\n\r\nexport default getDefaultExport(\r\n \"string\",\r\n stringTryParse,\r\n stringFunctions,\r\n options,\r\n typeConstraints,\r\n \"abcde\",\r\n str => str\r\n)\r\n"],"file":"string.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/types/typeHelpers.js.map b/packages/common/lib/schema/types/typeHelpers.js.map index ed19a398da..17b6e203ca 100644 --- a/packages/common/lib/schema/types/typeHelpers.js.map +++ b/packages/common/lib/schema/types/typeHelpers.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/schema/types/typeHelpers.js"],"names":["getSafeFieldParser","tryParse","defaultValueFunctions","field","record","name","getSafeValueParser","getUndefinedValue","value","parsed","success","getNewValue","getInitialValue","typeFunctions","specificFunctions","constant","validateTypeConstraints","validationRules","fieldValue","validateRule","r","isValid","typeOptions","getMessage","errors","err","push","getDefaultOptions","v","defaultValue","makerule","parsedFailed","val","parsedSuccess","getDefaultExport","functions","options","sampleValue","stringify","getNew","safeParseField","safeParseValue","optionDefinitions","undefined","getDefaultValue"],"mappings":"yTAAA;AACA;AACA,8C;;AAEO,IAAMA,kBAAkB,GAAG,SAArBA,kBAAqB,CAACC,QAAD,EAAWC,qBAAX,UAAqC;AACrEC,EAAAA,KADqE;AAErEC,EAAAA,MAFqE;AAGlE;AACH,QAAI,aAAID,KAAK,CAACE,IAAV,EAAgBD,MAAhB,CAAJ,EAA6B;AAC3B,aAAOE,kBAAkB;AACvBL,MAAAA,QADuB;AAEvBC,MAAAA,qBAFuB,CAAlB;AAGLE,MAAAA,MAAM,CAACD,KAAK,CAACE,IAAP,CAHD,CAAP;AAID;AACD,WAAOH,qBAAqB,CAACC,KAAK,CAACI,iBAAP,CAArB,EAAP;AACD,GAXiC,EAA3B,C;;AAaA,IAAMD,kBAAkB,GAAG,SAArBA,kBAAqB;AAChCL,QADgC;AAEhCC,qBAFgC;AAG7B,cAAAM,KAAK,EAAI;AACZ,UAAMC,MAAM,GAAGR,QAAQ,CAACO,KAAD,CAAvB;AACA,UAAIC,MAAM,CAACC,OAAX,EAAoB;AAClB,eAAOD,MAAM,CAACD,KAAd;AACD;AACD,aAAON,qBAAqB,WAArB,EAAP;AACD,KATiC,GAA3B,C;;AAWA,IAAMS,WAAW,GAAG,SAAdA,WAAc,CAACV,QAAD,EAAWC,qBAAX,UAAqC,UAAAC,KAAK,EAAI;AACvE,QAAMS,eAAe;AACnB,yBAAYT,KAAZ,KAAsB,qBAAYA,KAAK,CAACS,eAAlB,CAAtB;AACI,aADJ;AAEIT,IAAAA,KAAK,CAACS,eAHZ;;AAKA,WAAO,aAAIA,eAAJ,EAAqBV,qBAArB;AACHA,IAAAA,qBAAqB,CAACU,eAAD,CAArB,EADG;AAEHN,IAAAA,kBAA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,KAAX,EAAkBF,KAAK,EAAEwB,GAAzB,EAAL,EAAxB,C;AACA,IAAMC,aAAa,GAAG,SAAhBA,aAAgB,CAAAD,GAAG,UAAK,EAAEtB,OAAO,EAAE,IAAX,EAAiBF,KAAK,EAAEwB,GAAxB,EAAL,EAAzB,C;AACA,IAAME,gBAAgB,GAAG,SAAnBA,gBAAmB;AAC9B7B,IAD8B;AAE9BJ,QAF8B;AAG9BkC,SAH8B;AAI9BC,OAJ8B;AAK9BnB,eAL8B;AAM9BoB,WAN8B;AAO9BC,UAP8B;AAQ1B;AACJC,MAAAA,MAAM,EAAE5B,WAAW,CAACV,QAAD,EAAWkC,SAAX,CADf;AAEJK,MAAAA,cAAc,EAAExC,kBAAkB,CAACC,QAAD,EAAWkC,SAAX,CAF9B;AAGJM,MAAAA,cAAc,EAAEnC,kBAAkB,CAACL,QAAD,EAAWkC,SAAX,CAH9B;AAIJlC,MAAAA,QAAQ,EAARA,QAJI;AAKJI,MAAAA,IAAI,EAAJA,IALI;AAMJsB,MAAAA,iBAAiB,EAAE,qCAAMA,kBAAiB,CAAC,mBAAUS,OAAV,CAAD,CAAvB,EANf;AAOJM,MAAAA,iBAAiB,EAAEN,OAPf;AAQJpB,MAAAA,uBAAuB,EAAEA,uBAAuB,CAACC,eAAD,CAR5C;AASJoB,MAAAA,WAAW,EAAXA,WATI;AAUJC,MAAAA,SAAS,EAAE,mBAAAN,GAAG,UAAKA,GAAG,KAAK,IAAR,IAAgBA,GAAG,KAAKW,SAAxB,GAAoC,EAApC,GAAyCL,UAAS,CAACN,GAAD,CAAvD,EAVV;AAWJY,MAAAA,eAAe,EAAET,SAAS,WAXtB,EAR0B,GAAzB,C","sourcesContent":["import { merge } from \"lodash\"\nimport { constant, isUndefined, has, mapValues, cloneDeep } from \"lodash/fp\"\nimport { isNotEmpty } from \"../../common/index.js\"\n\nexport const getSafeFieldParser = (tryParse, defaultValueFunctions) => (\n field,\n record\n) => {\n if (has(field.name)(record)) {\n return getSafeValueParser(\n tryParse,\n defaultValueFunctions\n )(record[field.name])\n }\n return defaultValueFunctions[field.getUndefinedValue]()\n}\n\nexport const getSafeValueParser = (\n tryParse,\n defaultValueFunctions\n) => value => {\n const parsed = tryParse(value)\n if (parsed.success) {\n return parsed.value\n }\n return defaultValueFunctions.default()\n}\n\nexport const getNewValue = (tryParse, defaultValueFunctions) => field => {\n const getInitialValue =\n isUndefined(field) || isUndefined(field.getInitialValue)\n ? \"default\"\n : field.getInitialValue\n\n return has(getInitialValue)(defaultValueFunctions)\n ? defaultValueFunctions[getInitialValue]()\n : getSafeValueParser(tryParse, defaultValueFunctions)(getInitialValue)\n}\n\nexport const typeFunctions = specificFunctions =>\n merge(\n {\n value: constant,\n null: constant(null),\n },\n specificFunctions\n )\n\nexport const validateTypeConstraints = validationRules => (field, record) => {\n const fieldValue = record[field.name]\n const validateRule = r =>\n !r.isValid(fieldValue, field.typeOptions)\n ? r.getMessage(fieldValue, field.typeOptions)\n : \"\"\n\n const errors = []\n for (const r of validationRules) {\n const err = validateRule(r)\n if (isNotEmpty(err)) errors.push(err)\n }\n\n return errors\n}\n\nconst getDefaultOptions = mapValues(v => v.defaultValue)\n\nexport const makerule = (isValid, getMessage) => ({ isValid, getMessage })\nexport const parsedFailed = val => ({ success: false, value: val })\nexport const parsedSuccess = val => ({ success: true, value: val })\nexport const getDefaultExport = (\n name,\n tryParse,\n functions,\n options,\n validationRules,\n sampleValue,\n stringify\n) => ({\n getNew: getNewValue(tryParse, functions),\n safeParseField: getSafeFieldParser(tryParse, functions),\n safeParseValue: getSafeValueParser(tryParse, functions),\n tryParse,\n name,\n getDefaultOptions: () => getDefaultOptions(cloneDeep(options)),\n optionDefinitions: options,\n validateTypeConstraints: validateTypeConstraints(validationRules),\n sampleValue,\n stringify: val => (val === null || val === undefined ? \"\" : stringify(val)),\n getDefaultValue: functions.default,\n})\n"],"file":"typeHelpers.js"} \ No newline at end of file +{"version":3,"sources":["../../../src/schema/types/typeHelpers.js"],"names":["getSafeFieldParser","tryParse","defaultValueFunctions","field","record","name","getSafeValueParser","getUndefinedValue","value","parsed","success","getNewValue","getInitialValue","typeFunctions","specificFunctions","constant","validateTypeConstraints","validationRules","fieldValue","validateRule","r","isValid","typeOptions","getMessage","errors","err","push","getDefaultOptions","v","defaultValue","makerule","parsedFailed","val","parsedSuccess","getDefaultExport","functions","options","sampleValue","stringify","getNew","safeParseField","safeParseValue","optionDefinitions","undefined","getDefaultValue"],"mappings":"yTAAA;AACA;AACA,8C;;AAEO,IAAMA,kBAAkB,GAAG,SAArBA,kBAAqB,CAACC,QAAD,EAAWC,qBAAX,UAAqC;AACrEC,EAAAA,KADqE;AAErEC,EAAAA,MAFqE;AAGlE;AACH,QAAI,aAAID,KAAK,CAACE,IAAV,EAAgBD,MAAhB,CAAJ,EAA6B;AAC3B,aAAOE,kBAAkB;AACvBL,MAAAA,QADuB;AAEvBC,MAAAA,qBAFuB,CAAlB;AAGLE,MAAAA,MAAM,CAACD,KAAK,CAACE,IAAP,CAHD,CAAP;AAID;AACD,WAAOH,qBAAqB,CAACC,KAAK,CAACI,iBAAP,CAArB,EAAP;AACD,GAXiC,EAA3B,C;;AAaA,IAAMD,kBAAkB,GAAG,SAArBA,kBAAqB;AAChCL,QADgC;AAEhCC,qBAFgC;AAG7B,cAAAM,KAAK,EAAI;AACZ,UAAMC,MAAM,GAAGR,QAAQ,CAACO,KAAD,CAAvB;AACA,UAAIC,MAAM,CAACC,OAAX,EAAoB;AAClB,eAAOD,MAAM,CAACD,KAAd;AACD;AACD,aAAON,qBAAqB,WAArB,EAAP;AACD,KATiC,GAA3B,C;;AAWA,IAAMS,WAAW,GAAG,SAAdA,WAAc,CAACV,QAAD,EAAWC,qBAAX,UAAqC,UAAAC,KAAK,EAAI;AACvE,QAAMS,eAAe;AACnB,yBAAYT,KAAZ,KAAsB,qBAAYA,KAAK,CAACS,eAAlB,CAAtB;AACI,aADJ;AAEIT,IAAAA,KAAK,CAACS,eAHZ;;AAKA,WAAO,aAAIA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,EAAjB,C;AACA,IAAMQ,YAAY,GAAG,SAAfA,YAAe,CAAAC,GAAG,UAAK,EAAEtB,OAAO,EAAE,KAAX,EAAkBF,KAAK,EAAEwB,GAAzB,EAAL,EAAxB,C;AACA,IAAMC,aAAa,GAAG,SAAhBA,aAAgB,CAAAD,GAAG,UAAK,EAAEtB,OAAO,EAAE,IAAX,EAAiBF,KAAK,EAAEwB,GAAxB,EAAL,EAAzB,C;AACA,IAAME,gBAAgB,GAAG,SAAnBA,gBAAmB;AAC9B7B,IAD8B;AAE9BJ,QAF8B;AAG9BkC,SAH8B;AAI9BC,OAJ8B;AAK9BnB,eAL8B;AAM9BoB,WAN8B;AAO9BC,UAP8B;AAQ1B;AACJC,MAAAA,MAAM,EAAE5B,WAAW,CAACV,QAAD,EAAWkC,SAAX,CADf;AAEJK,MAAAA,cAAc,EAAExC,kBAAkB,CAACC,QAAD,EAAWkC,SAAX,CAF9B;AAGJM,MAAAA,cAAc,EAAEnC,kBAAkB,CAACL,QAAD,EAAWkC,SAAX,CAH9B;AAIJlC,MAAAA,QAAQ,EAARA,QAJI;AAKJI,MAAAA,IAAI,EAAJA,IALI;AAMJsB,MAAAA,iBAAiB,EAAE,qCAAMA,kBAAiB,CAAC,mBAAUS,OAAV,CAAD,CAAvB,EANf;AAOJM,MAAAA,iBAAiB,EAAEN,OAPf;AAQJpB,MAAAA,uBAAuB,EAAEA,uBAAuB,CAACC,eAAD,CAR5C;AASJoB,MAAAA,WAAW,EAAXA,WATI;AAUJC,MAAAA,SAAS,EAAE,mBAAAN,GAAG,UAAKA,GAAG,KAAK,IAAR,IAAgBA,GAAG,KAAKW,SAAxB,GAAoC,EAApC,GAAyCL,UAAS,CAACN,GAAD,CAAvD,EAVV;AAWJY,MAAAA,eAAe,EAAET,SAAS,WAXtB,EAR0B,GAAzB,C","sourcesContent":["import { merge } from \"lodash\"\r\nimport { constant, isUndefined, has, mapValues, cloneDeep } from \"lodash/fp\"\r\nimport { isNotEmpty } from \"../../common/index.js\"\r\n\r\nexport const getSafeFieldParser = (tryParse, defaultValueFunctions) => (\r\n field,\r\n record\r\n) => {\r\n if (has(field.name)(record)) {\r\n return getSafeValueParser(\r\n tryParse,\r\n defaultValueFunctions\r\n )(record[field.name])\r\n }\r\n return defaultValueFunctions[field.getUndefinedValue]()\r\n}\r\n\r\nexport const getSafeValueParser = (\r\n tryParse,\r\n defaultValueFunctions\r\n) => value => {\r\n const parsed = tryParse(value)\r\n if (parsed.success) {\r\n return parsed.value\r\n }\r\n return defaultValueFunctions.default()\r\n}\r\n\r\nexport const getNewValue = (tryParse, defaultValueFunctions) => field => {\r\n const getInitialValue =\r\n isUndefined(field) || isUndefined(field.getInitialValue)\r\n ? \"default\"\r\n : field.getInitialValue\r\n\r\n return has(getInitialValue)(defaultValueFunctions)\r\n ? defaultValueFunctions[getInitialValue]()\r\n : getSafeValueParser(tryParse, defaultValueFunctions)(getInitialValue)\r\n}\r\n\r\nexport const typeFunctions = specificFunctions =>\r\n merge(\r\n {\r\n value: constant,\r\n null: constant(null),\r\n },\r\n specificFunctions\r\n )\r\n\r\nexport const validateTypeConstraints = validationRules => (field, record) => {\r\n const fieldValue = record[field.name]\r\n const validateRule = r =>\r\n !r.isValid(fieldValue, field.typeOptions)\r\n ? r.getMessage(fieldValue, field.typeOptions)\r\n : \"\"\r\n\r\n const errors = []\r\n for (const r of validationRules) {\r\n const err = validateRule(r)\r\n if (isNotEmpty(err)) errors.push(err)\r\n }\r\n\r\n return errors\r\n}\r\n\r\nconst getDefaultOptions = mapValues(v => v.defaultValue)\r\n\r\nexport const makerule = (isValid, getMessage) => ({ isValid, getMessage })\r\nexport const parsedFailed = val => ({ success: false, value: val })\r\nexport const parsedSuccess = val => ({ success: true, value: val })\r\nexport const getDefaultExport = (\r\n name,\r\n tryParse,\r\n functions,\r\n options,\r\n validationRules,\r\n sampleValue,\r\n stringify\r\n) => ({\r\n getNew: getNewValue(tryParse, functions),\r\n safeParseField: getSafeFieldParser(tryParse, functions),\r\n safeParseValue: getSafeValueParser(tryParse, functions),\r\n tryParse,\r\n name,\r\n getDefaultOptions: () => getDefaultOptions(cloneDeep(options)),\r\n optionDefinitions: options,\r\n validateTypeConstraints: validateTypeConstraints(validationRules),\r\n sampleValue,\r\n stringify: val => (val === null || val === undefined ? \"\" : stringify(val)),\r\n getDefaultValue: functions.default,\r\n})\r\n"],"file":"typeHelpers.js"} \ No newline at end of file diff --git a/packages/common/lib/schema/views.js.map b/packages/common/lib/schema/views.js.map index 07be3044e4..cbdb6f6798 100644 --- a/packages/common/lib/schema/views.js.map +++ b/packages/common/lib/schema/views.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/schema/views.js"],"names":["newView","modelId","id","name"],"mappings":"oGAAA;;AAEO,IAAMA,OAAO,GAAG,SAAVA,OAAU,QAACC,OAAD,uEAAW,IAAX,QAAqB;AAC1CC,IAAAA,EAAE,EAAE,wBADsC;AAE1CC,IAAAA,IAAI,EAAE,EAFoC;AAG1CF,IAAAA,OAAO,EAAPA,OAH0C,EAArB,EAAhB,C","sourcesContent":["import { generate } from \"shortid\"\n\nexport const newView = (modelId = null) => ({\n id: generate(),\n name: \"\",\n modelId,\n})\n"],"file":"views.js"} \ No newline at end of file +{"version":3,"sources":["../../src/schema/views.js"],"names":["newView","modelId","id","name"],"mappings":"oGAAA;;AAEO,IAAMA,OAAO,GAAG,SAAVA,OAAU,QAACC,OAAD,uEAAW,IAAX,QAAqB;AAC1CC,IAAAA,EAAE,EAAE,wBADsC;AAE1CC,IAAAA,IAAI,EAAE,EAFoC;AAG1CF,IAAAA,OAAO,EAAPA,OAH0C,EAArB,EAAhB,C","sourcesContent":["import { generate } from \"shortid\"\r\n\r\nexport const newView = (modelId = null) => ({\r\n id: generate(),\r\n name: \"\",\r\n modelId,\r\n})\r\n"],"file":"views.js"} \ No newline at end of file diff --git a/packages/common/lib/schemaValidation/index.js.map b/packages/common/lib/schemaValidation/index.js.map index 009b82c4cf..1dfdf41881 100644 --- a/packages/common/lib/schemaValidation/index.js.map +++ b/packages/common/lib/schemaValidation/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/schemaValidation/index.js"],"names":["ajv","Ajv"],"mappings":"4LAAA;;AAEA,IAAMA,GAAG,GAAG,IAAIC,eAAJ,EAAZ,C;;AAEeD,G","sourcesContent":["import Ajv from \"ajv\";\n\nconst ajv = new Ajv();\n\nexport default ajv;"],"file":"index.js"} \ No newline at end of file +{"version":3,"sources":["../../src/schemaValidation/index.js"],"names":["ajv","Ajv"],"mappings":"4LAAA;;AAEA,IAAMA,GAAG,GAAG,IAAIC,eAAJ,EAAZ,C;;AAEeD,G","sourcesContent":["import Ajv from \"ajv\";\r\n\r\nconst ajv = new Ajv();\r\n\r\nexport default ajv;"],"file":"index.js"} \ No newline at end of file diff --git a/packages/common/src/records/getNewRecord.js b/packages/common/src/records/getNewRecord.js index 32a89c961c..785e3b092b 100644 --- a/packages/common/src/records/getNewRecord.js +++ b/packages/common/src/records/getNewRecord.js @@ -1,16 +1,15 @@ import { generate } from "shortid" -import { getNewFieldValue } from "../schema/types" export const getNewRecord = (schema, modelName) => { const model = schema.findModel(modelName) const record = { _id: generate(), - _modelId: model.id, + modelId: model._id, } - for (let field of model.fields) { - record[field.name] = getNewFieldValue(field) + for (let field in model.schema.properties) { + record[field] = field.default } return record diff --git a/packages/common/src/schema/models.js b/packages/common/src/schema/models.js index 105eef8193..ccef59623c 100644 --- a/packages/common/src/schema/models.js +++ b/packages/common/src/schema/models.js @@ -1,12 +1,17 @@ import { generate } from "shortid" export const newModel = () => ({ - id: generate(), + _id: generate(), name: "", - fields: [], - validationRules: [], - primaryField: "", - views: [], + type: "model", + key: "name", + schema: { + type: "object", + properties: { + name: { type: "string" }, + }, + required: ["name"], + }, }) /** diff --git a/packages/common/src/schema/types/array.js b/packages/common/src/schema/types/array.js deleted file mode 100644 index 44c820f517..0000000000 --- a/packages/common/src/schema/types/array.js +++ /dev/null @@ -1,68 +0,0 @@ -import { map, constant, isArray } from "lodash/fp" -import { - typeFunctions, - makerule, - parsedFailed, - getDefaultExport, - parsedSuccess, -} from "./typeHelpers" -import { - switchCase, - defaultCase, - toNumberOrNull, - $$, - isSafeInteger, -} from "../../common/index.js" - -const arrayFunctions = () => - typeFunctions({ - default: constant([]), - }) - -const mapToParsedArrary = type => - $$( - map(i => type.safeParseValue(i)), - parsedSuccess - ) - -const arrayTryParse = type => - switchCase([isArray, mapToParsedArrary(type)], [defaultCase, parsedFailed]) - -const typeName = type => `array<${type}>` - -const options = { - maxLength: { - defaultValue: 10000, - isValid: isSafeInteger, - requirementDescription: "must be a positive integer", - parse: toNumberOrNull, - }, - minLength: { - defaultValue: 0, - isValid: n => isSafeInteger(n) && n >= 0, - requirementDescription: "must be a positive integer", - parse: toNumberOrNull, - }, -} - -const typeConstraints = [ - makerule( - (val, opts) => val === null || val.length >= opts.minLength, - (val, opts) => `must choose ${opts.minLength} or more options` - ), - makerule( - (val, opts) => val === null || val.length <= opts.maxLength, - (val, opts) => `cannot choose more than ${opts.maxLength} options` - ), -] - -export default type => - getDefaultExport( - typeName(type.name), - arrayTryParse(type), - arrayFunctions(type), - options, - typeConstraints, - [type.sampleValue], - JSON.stringify - ) diff --git a/packages/common/src/schema/types/bool.js b/packages/common/src/schema/types/bool.js deleted file mode 100644 index c1bfa70141..0000000000 --- a/packages/common/src/schema/types/bool.js +++ /dev/null @@ -1,52 +0,0 @@ -import { constant, isBoolean, isNull } from "lodash/fp" -import { - typeFunctions, - makerule, - parsedFailed, - parsedSuccess, - getDefaultExport, -} from "./typeHelpers" -import { - switchCase, - defaultCase, - isOneOf, - toBoolOrNull, -} from "../../common/index.js" - -const boolFunctions = typeFunctions({ - default: constant(null), -}) - -const boolTryParse = switchCase( - [isBoolean, parsedSuccess], - [isNull, parsedSuccess], - [isOneOf("true", "1", "yes", "on"), () => parsedSuccess(true)], - [isOneOf("false", "0", "no", "off"), () => parsedSuccess(false)], - [defaultCase, parsedFailed] -) - -const options = { - allowNulls: { - defaultValue: true, - isValid: isBoolean, - requirementDescription: "must be a true or false", - parse: toBoolOrNull, - }, -} - -const typeConstraints = [ - makerule( - (val, opts) => opts.allowNulls === true || val !== null, - () => "field cannot be null" - ), -] - -export default getDefaultExport( - "bool", - boolTryParse, - boolFunctions, - options, - typeConstraints, - true, - JSON.stringify -) diff --git a/packages/common/src/schema/types/boolean.js b/packages/common/src/schema/types/boolean.js new file mode 100644 index 0000000000..8b5f12baed --- /dev/null +++ b/packages/common/src/schema/types/boolean.js @@ -0,0 +1,12 @@ +export default { + isType: schema => schema.type === "boolean", + fromSchema: schema => schema, + toSchema: field => ({ + type: "boolean", + default: field.default, + }), + default: () => ({ + type: "boolean", + default: false, + }), +} diff --git a/packages/common/src/schema/types/datetime.js b/packages/common/src/schema/types/datetime.js index 451b03bbe7..80efe286bb 100644 --- a/packages/common/src/schema/types/datetime.js +++ b/packages/common/src/schema/types/datetime.js @@ -1,78 +1,19 @@ -import { constant, isDate, isString, isNull } from "lodash/fp" -import { - makerule, - typeFunctions, - parsedFailed, - parsedSuccess, - getDefaultExport, -} from "./typeHelpers" -import { switchCase, defaultCase, toDateOrNull } from "../../common" +export default { + isType: schema => + schema.anyOf && + schema.anyOf.filter(s => s.type === "string" && s.format === "date-time") + .length > 0, -const dateFunctions = typeFunctions({ - default: constant(null), - now: () => new Date(), -}) - -const isValidDate = d => d instanceof Date && !isNaN(d) - -const parseStringToDate = s => - switchCase( - [isValidDate, parsedSuccess], - [defaultCase, parsedFailed] - )(new Date(s)) - -const isNullOrEmpty = d => isNull(d) || (d || "").toString() === "" - -const isDateOrEmpty = d => isDate(d) || isNullOrEmpty(d) - -const dateTryParse = switchCase( - [isDateOrEmpty, parsedSuccess], - [isString, parseStringToDate], - [defaultCase, parsedFailed] -) - -const options = { - maxValue: { - defaultValue: null, - //defaultValue: new Date(32503680000000), - isValid: isDateOrEmpty, - requirementDescription: "must be a valid date", - parse: toDateOrNull, - }, - minValue: { - defaultValue: null, - //defaultValue: new Date(-8520336000000), - isValid: isDateOrEmpty, - requirementDescription: "must be a valid date", - parse: toDateOrNull, - }, + fromSchema: schema => ({ + type: "datetime", + default: schema.default, + }), + toSchema: () => ({ + anyOf: [{ type: "string", format: "date-time" }, { const: "" }], + default: "", + }), + default: () => ({ + type: "datetime", + default: "", + }), } - -const typeConstraints = [ - makerule( - (val, opts) => - val === null || isNullOrEmpty(opts.minValue) || val >= opts.minValue, - (val, opts) => - `value (${val.toString()}) must be greater than or equal to ${ - opts.minValue - }` - ), - makerule( - (val, opts) => - val === null || isNullOrEmpty(opts.maxValue) || val <= opts.maxValue, - (val, opts) => - `value (${val.toString()}) must be less than or equal to ${ - opts.minValue - } options` - ), -] - -export default getDefaultExport( - "datetime", - dateTryParse, - dateFunctions, - options, - typeConstraints, - new Date(1984, 4, 1), - date => JSON.stringify(date).replace(new RegExp('"', "g"), "") -) diff --git a/packages/common/src/schema/types/file.js b/packages/common/src/schema/types/file.js deleted file mode 100644 index d0c08b7785..0000000000 --- a/packages/common/src/schema/types/file.js +++ /dev/null @@ -1,62 +0,0 @@ -import { last, has, isString, intersection, isNull, isNumber } from "lodash/fp" -import { - typeFunctions, - parsedFailed, - parsedSuccess, - getDefaultExport, -} from "./typeHelpers" -import { - switchCase, - defaultCase, - none, - $, - splitKey, -} from "../../common/index.js" - -const illegalCharacters = "*?\\/:<>|\0\b\f\v" - -export const isLegalFilename = filePath => { - const fn = fileName(filePath) - return ( - fn.length <= 255 && - intersection(fn.split(""))(illegalCharacters.split("")).length === 0 && - none(f => f === "..")(splitKey(filePath)) - ) -} - -const fileNothing = () => ({ relativePath: "", size: 0 }) - -const fileFunctions = typeFunctions({ - default: fileNothing, -}) - -const fileTryParse = v => - switchCase( - [isValidFile, parsedSuccess], - [isNull, () => parsedSuccess(fileNothing())], - [defaultCase, parsedFailed] - )(v) - -const fileName = filePath => $(filePath, [splitKey, last]) - -const isValidFile = f => - !isNull(f) && - has("relativePath")(f) && - has("size")(f) && - isNumber(f.size) && - isString(f.relativePath) && - isLegalFilename(f.relativePath) - -const options = {} - -const typeConstraints = [] - -export default getDefaultExport( - "file", - fileTryParse, - fileFunctions, - options, - typeConstraints, - { relativePath: "some_file.jpg", size: 1000 }, - JSON.stringify -) diff --git a/packages/common/src/schema/types/index.js b/packages/common/src/schema/types/index.js index aae0dd3cc5..433eb0850a 100644 --- a/packages/common/src/schema/types/index.js +++ b/packages/common/src/schema/types/index.js @@ -1,84 +1,53 @@ -import { assign, merge } from "lodash" -import { - map, - isString, - isNumber, - isBoolean, - isDate, - keys, - isObject, - isArray, - has, -} from "lodash/fp" -import { $ } from "../../common" -import { parsedSuccess } from "./typeHelpers" -import string from "./string" -import bool from "./bool" -import number from "./number" +import boolean from "./boolean" import datetime from "./datetime" -import array from "./array" import link from "./link" -import file from "./file" -import { BadRequestError } from "../../common/errors" +import number from "./number" +import select from "./select" +import text from "./text" -const allTypes = () => { - const basicTypes = { - string, - number, - datetime, - bool, - link, - file, +const allTypes = { + boolean, + datetime, + link, + number, + select, + text, +} + +export function listTypes() { + return Object.keys(allTypes) +} + +export function newField(name, type) { + const field = allTypes[type].default() + field.name = name + field.required = false + return field +} + +export function fieldsToSchema(fields) { + const required = fields.filter(f => f.required).map(f => f.name) + + return { + type: "object", + required, + properties: fields.reduce((sch, field) => { + sch[field.name] = allTypes[field.type].toSchema(field) + return sch + }, {}), } - - const arrays = $(basicTypes, [ - keys, - map(k => { - const kvType = {} - const concreteArray = array(basicTypes[k]) - kvType[concreteArray.name] = concreteArray - return kvType - }), - types => assign({}, ...types), - ]) - - return merge({}, basicTypes, arrays) } -export const all = allTypes() - -export const getType = typeName => { - if (!has(typeName)(all)) - throw new BadRequestError(`Do not recognise type ${typeName}`) - return all[typeName] -} - -export const getSampleFieldValue = field => getType(field.type).sampleValue - -export const getNewFieldValue = field => getType(field.type).getNew(field) - -export const safeParseField = (field, record) => - getType(field.type).safeParseField(field, record) - -export const validateFieldParse = (field, record) => - has(field.name)(record) - ? getType(field.type).tryParse(record[field.name]) - : parsedSuccess(undefined) // fields may be undefined by default - -export const getDefaultOptions = type => getType(type).getDefaultOptions() - -export const validateTypeConstraints = (field, record) => - getType(field.type).validateTypeConstraints(field, record) - -export const detectType = value => { - if (isString(value)) return string - if (isBoolean(value)) return bool - if (isNumber(value)) return number - if (isDate(value)) return datetime - if (isArray(value)) return array(detectType(value[0])) - if (isObject(value) && has("key")(value) && has("value")(value)) return link - if (isObject(value) && has("relativePath")(value) && has("size")(value)) - return file - - throw new BadRequestError(`cannot determine type: ${JSON.stringify(value)}`) +export function schemaToFields(modelSchema) { + return Object.keys(modelSchema.properties).map(key => { + const schema = modelSchema.properties[key] + for (let type in allTypes) { + if (allTypes[type].isType(schema)) { + const field = allTypes[type].fromSchema(schema) + field.required = modelSchema.required.includes(key) + field.name = key + return field + } + } + }) } diff --git a/packages/common/src/schema/types/link.js b/packages/common/src/schema/types/link.js index a2f1b2cf63..deaa895c25 100644 --- a/packages/common/src/schema/types/link.js +++ b/packages/common/src/schema/types/link.js @@ -1,42 +1,27 @@ -import { isString, isUndefined, isNull } from "lodash/fp" -import { typeFunctions, parsedSuccess, getDefaultExport } from "./typeHelpers" -import { - switchCase, - defaultCase, - isNonEmptyString, -} from "../../common/index.js" +export default { + isType: schema => schema.type === "object" && schema.properties.modelId, -const linkNothing = () => "" + fromSchema: schema => ({ + type: "link", + modelId: schema.properties.modelId.const, + viewId: schema.properties.viewId.const, + default: schema.default, + }), -const linkFunctions = typeFunctions({ - default: linkNothing, -}) + toSchema: field => ({ + type: "object", + properties: { + _id: { type: "string" }, + viewId: field.viewId ? { const: field.viewId } : undefined, + modelId: field.modelId ? { const: field.modelId } : undefined, + }, + required: ["_id"], + default: { _id: "" }, + }), -const linkTryParse = v => - switchCase( - [isString, s => parsedSuccess(s)], - [isNull, () => parsedSuccess(linkNothing())], - [isUndefined, () => parsedSuccess(linkNothing())], - [defaultCase, s => parsedSuccess(s.toString())] - )(v) - -const options = { - modelId: { - defaultValue: "", - isValid: isNonEmptyString, - requirementDescription: "must choose a model", - parse: s => s, - }, + default: () => ({ + type: "link", + modelId: null, + viewId: null, + }), } - -const typeConstraints = [] - -export default getDefaultExport( - "link", - linkTryParse, - linkFunctions, - options, - typeConstraints, - "abcd1234", - JSON.stringify -) diff --git a/packages/common/src/schema/types/number.js b/packages/common/src/schema/types/number.js index 2fdcf1ac4f..94733bace1 100644 --- a/packages/common/src/schema/types/number.js +++ b/packages/common/src/schema/types/number.js @@ -1,94 +1,15 @@ -import { constant, isNumber, isString, isNull } from "lodash/fp" -import { - makerule, - typeFunctions, - parsedFailed, - parsedSuccess, - getDefaultExport, -} from "./typeHelpers" -import { - switchCase, - defaultCase, - toNumberOrNull, - isSafeInteger, -} from "../../common/index.js" - -const numberFunctions = typeFunctions({ - default: constant(null), -}) - -const parseStringtoNumberOrNull = s => { - const num = Number(s) - return isNaN(num) ? parsedFailed(s) : parsedSuccess(num) +export default { + isType: schema => schema.type === "number", + fromSchema: schema => schema, + toSchema: field => ({ + type: "number", + maximum: field.maximum, + minimum: field.minimum, + default: undefined, + }), + default: () => ({ + type: "number", + maximum: null, + minimum: null, + }), } - -const numberTryParse = switchCase( - [isNumber, parsedSuccess], - [isString, parseStringtoNumberOrNull], - [isNull, parsedSuccess], - [defaultCase, parsedFailed] -) - -const options = { - maxValue: { - defaultValue: Number.MAX_SAFE_INTEGER, - isValid: isSafeInteger, - requirementDescription: "must be a valid integer", - parse: toNumberOrNull, - }, - minValue: { - defaultValue: 0 - Number.MAX_SAFE_INTEGER, - isValid: isSafeInteger, - requirementDescription: "must be a valid integer", - parse: toNumberOrNull, - }, - decimalPlaces: { - defaultValue: 0, - isValid: n => isSafeInteger(n) && n >= 0, - requirementDescription: "must be a positive integer", - parse: toNumberOrNull, - }, -} - -const getDecimalPlaces = val => { - const splitDecimal = val.toString().split(".") - if (splitDecimal.length === 1) return 0 - return splitDecimal[1].length -} - -const typeConstraints = [ - makerule( - (val, opts) => - val === null || opts.minValue === null || val >= opts.minValue, - (val, opts) => - `value (${val.toString()}) must be greater than or equal to ${ - opts.minValue - }` - ), - makerule( - (val, opts) => - val === null || opts.maxValue === null || val <= opts.maxValue, - (val, opts) => - `value (${val.toString()}) must be less than or equal to ${ - opts.minValue - } options` - ), - makerule( - (val, opts) => - val === null || opts.decimalPlaces >= getDecimalPlaces(val), - (val, opts) => - `value (${val.toString()}) must have ${ - opts.decimalPlaces - } decimal places or less` - ), -] - -export default getDefaultExport( - "number", - numberTryParse, - numberFunctions, - options, - typeConstraints, - 1, - num => num.toString() -) diff --git a/packages/common/src/schema/types/object.js b/packages/common/src/schema/types/object.js deleted file mode 100644 index d1429d1af7..0000000000 --- a/packages/common/src/schema/types/object.js +++ /dev/null @@ -1,59 +0,0 @@ -import { keys, isObject, has, clone, map, isNull, constant } from "lodash" -import { - typeFunctions, - parsedFailed, - parsedSuccess, - getDefaultExport, -} from "./typeHelpers" -import { switchCase, defaultCase, $ } from "../../common/index.js" - -const objectFunctions = (definition, allTypes) => - typeFunctions({ - default: constant(null), - initialise: () => - $(keys(definition), [ - map(() => { - const defClone = clone(definition) - for (const k in defClone) { - defClone[k] = allTypes[k].getNew() - } - return defClone - }), - ]), - }) - -const parseObject = (definition, allTypes) => record => { - const defClone = clone(definition) - for (const k in defClone) { - const type = allTypes[defClone[k]] - defClone[k] = has(record, k) - ? type.safeParseValue(record[k]) - : type.getNew() - } - return parsedSuccess(defClone) -} - -const objectTryParse = (definition, allTypes) => - switchCase( - [isNull, parsedSuccess], - [isObject, parseObject(definition, allTypes)], - [defaultCase, parsedFailed] - ) - -export default ( - typeName, - definition, - allTypes, - defaultOptions, - typeConstraints, - sampleValue -) => - getDefaultExport( - typeName, - objectTryParse(definition, allTypes), - objectFunctions(definition, allTypes), - defaultOptions, - typeConstraints, - sampleValue, - JSON.stringify - ) diff --git a/packages/common/src/schema/types/select.js b/packages/common/src/schema/types/select.js new file mode 100644 index 0000000000..0deb998f99 --- /dev/null +++ b/packages/common/src/schema/types/select.js @@ -0,0 +1,21 @@ +export default { + isType: schema => schema.type === "string" && schema.enum, + + fromSchema: schema => ({ + type: "select", + enum: schema.enum, + default: schema.default, + }), + + toSchema: field => ({ + type: "string", + enum: field.enum, + default: field.default, + }), + + default: () => ({ + type: "select", + enum: [], + default: "", + }), +} diff --git a/packages/common/src/schema/types/string.js b/packages/common/src/schema/types/string.js deleted file mode 100644 index 2c19cb8ce5..0000000000 --- a/packages/common/src/schema/types/string.js +++ /dev/null @@ -1,74 +0,0 @@ -import { constant, isString, isNull, includes, isBoolean } from "lodash/fp" -import { - typeFunctions, - makerule, - parsedSuccess, - getDefaultExport, -} from "./typeHelpers" -import { - switchCase, - defaultCase, - toBoolOrNull, - toNumberOrNull, - isSafeInteger, - isArrayOfString, -} from "../../common/index.js" - -const stringFunctions = typeFunctions({ - default: constant(null), -}) - -const stringTryParse = switchCase( - [isString, parsedSuccess], - [isNull, parsedSuccess], - [defaultCase, v => parsedSuccess(v.toString())] -) - -const options = { - maxLength: { - defaultValue: null, - isValid: n => n === null || (isSafeInteger(n) && n > 0), - requirementDescription: - "max length must be null (no limit) or a greater than zero integer", - parse: toNumberOrNull, - }, - values: { - defaultValue: null, - isValid: v => - v === null || (isArrayOfString(v) && v.length > 0 && v.length < 10000), - requirementDescription: - "'values' must be null (no values) or an array of at least one string", - parse: s => s, - }, - allowDeclaredValuesOnly: { - defaultValue: false, - isValid: isBoolean, - requirementDescription: "allowDeclaredValuesOnly must be true or false", - parse: toBoolOrNull, - }, -} - -const typeConstraints = [ - makerule( - (val, opts) => - val === null || opts.maxLength === null || val.length <= opts.maxLength, - (val, opts) => `value exceeds maximum length of ${opts.maxLength}` - ), - makerule( - (val, opts) => - val === null || - opts.allowDeclaredValuesOnly === false || - includes(val)(opts.values), - val => `"${val}" does not exist in the list of allowed values` - ), -] - -export default getDefaultExport( - "string", - stringTryParse, - stringFunctions, - options, - typeConstraints, - "abcde", - str => str -) diff --git a/packages/common/src/schema/types/text.js b/packages/common/src/schema/types/text.js new file mode 100644 index 0000000000..eb0c938b42 --- /dev/null +++ b/packages/common/src/schema/types/text.js @@ -0,0 +1,24 @@ +export default { + isType: schema => schema.type === "string" && !schema.format, + + fromSchema: schema => ({ + type: "text", + maxLength: schema.maxLength, + minLength: schema.minLength, + default: schema.default, + }), + + toSchema: field => ({ + type: "string", + maxLength: field.maxLength, + minLength: field.minLength, + default: "", + }), + + default: () => ({ + type: "text", + maxLength: null, + minLength: 0, + default: "", + }), +} diff --git a/packages/common/src/schema/types/typeHelpers.js b/packages/common/src/schema/types/typeHelpers.js deleted file mode 100644 index 0d5e1b07f0..0000000000 --- a/packages/common/src/schema/types/typeHelpers.js +++ /dev/null @@ -1,90 +0,0 @@ -import { merge } from "lodash" -import { constant, isUndefined, has, mapValues, cloneDeep } from "lodash/fp" -import { isNotEmpty } from "../../common/index.js" - -export const getSafeFieldParser = (tryParse, defaultValueFunctions) => ( - field, - record -) => { - if (has(field.name)(record)) { - return getSafeValueParser( - tryParse, - defaultValueFunctions - )(record[field.name]) - } - return defaultValueFunctions[field.getUndefinedValue]() -} - -export const getSafeValueParser = ( - tryParse, - defaultValueFunctions -) => value => { - const parsed = tryParse(value) - if (parsed.success) { - return parsed.value - } - return defaultValueFunctions.default() -} - -export const getNewValue = (tryParse, defaultValueFunctions) => field => { - const getInitialValue = - isUndefined(field) || isUndefined(field.getInitialValue) - ? "default" - : field.getInitialValue - - return has(getInitialValue)(defaultValueFunctions) - ? defaultValueFunctions[getInitialValue]() - : getSafeValueParser(tryParse, defaultValueFunctions)(getInitialValue) -} - -export const typeFunctions = specificFunctions => - merge( - { - value: constant, - null: constant(null), - }, - specificFunctions - ) - -export const validateTypeConstraints = validationRules => (field, record) => { - const fieldValue = record[field.name] - const validateRule = r => - !r.isValid(fieldValue, field.typeOptions) - ? r.getMessage(fieldValue, field.typeOptions) - : "" - - const errors = [] - for (const r of validationRules) { - const err = validateRule(r) - if (isNotEmpty(err)) errors.push(err) - } - - return errors -} - -const getDefaultOptions = mapValues(v => v.defaultValue) - -export const makerule = (isValid, getMessage) => ({ isValid, getMessage }) -export const parsedFailed = val => ({ success: false, value: val }) -export const parsedSuccess = val => ({ success: true, value: val }) -export const getDefaultExport = ( - name, - tryParse, - functions, - options, - validationRules, - sampleValue, - stringify -) => ({ - getNew: getNewValue(tryParse, functions), - safeParseField: getSafeFieldParser(tryParse, functions), - safeParseValue: getSafeValueParser(tryParse, functions), - tryParse, - name, - getDefaultOptions: () => getDefaultOptions(cloneDeep(options)), - optionDefinitions: options, - validateTypeConstraints: validateTypeConstraints(validationRules), - sampleValue, - stringify: val => (val === null || val === undefined ? "" : stringify(val)), - getDefaultValue: functions.default, -}) diff --git a/packages/common/src/testUtils/testSchema.js b/packages/common/src/testUtils/testSchema.js new file mode 100644 index 0000000000..bb2613926f --- /dev/null +++ b/packages/common/src/testUtils/testSchema.js @@ -0,0 +1,38 @@ +import { newModel } from "../schema/models" +import { newView } from "../schema/views" +import { fullSchema } from "../schema/fullSchema" +import { newField, schemaToFields, fieldsToSchema } from "../schema/types" + +export function testSchema() { + const addFieldToModel = (model, field) => { + const defaultField = newField(field.name, field.type || "text") + Object.assign(defaultField, field) + const currentFields = schemaToFields(model.schema) + model.schema = fieldsToSchema([...currentFields, field]) + } + + const contactModel = newModel() + contactModel.name = "Contact" + addFieldToModel(contactModel, { name: "Is Active", type: "boolean" }) + addFieldToModel(contactModel, { name: "Created", type: "datetime" }) + addFieldToModel(contactModel, { + name: "Status", + type: "select", + enum: ["new", "complete"], + }) + + const activeContactsView = newView(contactModel.id) + activeContactsView.name = "Active Contacts" + activeContactsView.map = "if (doc['Is Active']) emit(doc.Name, doc)" + + const dealModel = newModel() + dealModel.name = "Deal" + addFieldToModel(dealModel, { name: "Estimated Value", type: "number" }) + addFieldToModel(dealModel, { + name: "Contact", + type: "link", + modelId: contactModel.id, + }) + + return fullSchema([contactModel, dealModel], [activeContactsView]) +} diff --git a/packages/common/test/templateApi.types.spec.js b/packages/common/test/templateApi.types.spec.js deleted file mode 100644 index 222bd38116..0000000000 --- a/packages/common/test/templateApi.types.spec.js +++ /dev/null @@ -1,285 +0,0 @@ -import { getNewFieldValue, safeParseField } from "../src/types" -import { getNewField } from "../src/templateApi/fields" -import { isDefined } from "../src/common" - -const getField = type => { - const field = getNewField(type) - return field -} - -const nothingReference = { key: "" } -const nothingFile = { relativePath: "", size: 0 } - -describe("types > getNew", () => { - const defaultAlwaysNull = type => () => { - const field = getField(type) - field.getInitialValue = "default" - const value = getNewFieldValue(field) - expect(value).toBe(null) - } - - it( - "bool should return null when fields getInitialValue is 'default'", - defaultAlwaysNull("bool") - ) - - it( - "string should return null when fields getInitialValue is 'default'", - defaultAlwaysNull("string") - ) - - it( - "number should return null when fields getInitialValue is 'default'", - defaultAlwaysNull("number") - ) - - it( - "datetime should return null when fields getInitialValue is 'default'", - defaultAlwaysNull("datetime") - ) - - it("reference should return {key:''} when fields getInitialValue is 'default'", () => { - const field = getField("reference") - field.getInitialValue = "default" - const value = getNewFieldValue(field) - expect(value).toEqual(nothingReference) - }) - - it("file should return {relativePath:'', size:0} when fields getInitialValue is 'default'", () => { - const field = getField("file") - field.getInitialValue = "default" - const value = getNewFieldValue(field) - expect(value).toEqual(nothingFile) - }) - - it("array should return empty array when field getInitialValue is 'default'", () => { - const field = getField("array") - field.getInitialValue = "default" - const value = getNewFieldValue(field) - expect(value).toEqual([]) - }) - - it("datetime should return Now when getInitialValue is 'now'", () => { - const field = getField("datetime") - field.getInitialValue = "now" - const before = new Date() - const value = getNewFieldValue(field) - const after = new Date() - expect(value >= before && value <= after).toBeTruthy() - }) - - const test_getNewFieldValue = (type, val, expected) => () => { - const field = getField(type) - field.getInitialValue = val - const value = getNewFieldValue(field) - expect(value).toEqual(expected) - } - - it("bool should parse value in getInitialValue if function not recognised", () => { - test_getNewFieldValue("bool", "true", true)() - test_getNewFieldValue("bool", "on", true)() - test_getNewFieldValue("bool", "1", true)() - test_getNewFieldValue("bool", "yes", true)() - test_getNewFieldValue("bool", "false", false)() - test_getNewFieldValue("bool", "off", false)() - test_getNewFieldValue("bool", "0", false)() - test_getNewFieldValue("bool", "no", false)() - }) - - it("bool should return null if function not recognised and value cannot be parsed", () => { - test_getNewFieldValue("bool", "blah", null)() - test_getNewFieldValue("bool", 111, null)() - }) - - it("number should parse value in getInitialValue if function not recognised", () => { - test_getNewFieldValue("number", "1", 1)() - test_getNewFieldValue("number", "45", 45)() - test_getNewFieldValue("number", "4.11", 4.11)() - }) - - it("number should return null if function not recognised and value cannot be parsed", () => { - test_getNewFieldValue("number", "blah", null)() - test_getNewFieldValue("number", true, null)() - }) - - it("string should parse value in getInitialValue if function not recognised", () => { - test_getNewFieldValue("string", "hello there", "hello there")() - test_getNewFieldValue("string", 45, "45")() - test_getNewFieldValue("string", true, "true")() - }) - - it("array should return empty array when function not recognised", () => { - test_getNewFieldValue("array", "blah", [])() - test_getNewFieldValue("array", true, [])() - test_getNewFieldValue("array", 1, [])() - test_getNewFieldValue("array", "", [])() - test_getNewFieldValue("array", "", [])() - test_getNewFieldValue("array", "", [])() - }) - - it("reference should {key:''} when function not recognised", () => { - test_getNewFieldValue("reference", "blah", nothingReference)() - }) - - it("file should return {relativePath:'',size:0} when function not recognised", () => { - test_getNewFieldValue("file", "blah", nothingFile)() - }) -}) - -describe("types > getSafeFieldValue", () => { - const test_getSafeFieldValue = (type, member, value, expectedParse) => () => { - const field = getField(type) - field.getDefaultValue = "default" - field.name = member - const record = {} - if (isDefined(value)) record[member] = value - const parsedvalue = safeParseField(field, record) - expect(parsedvalue).toEqual(expectedParse) - } - - it( - "should get default field value when member is undefined on record", - test_getSafeFieldValue("string", "forename", undefined, null) - ) - - it("should return null as null (except array and reference)", () => { - test_getSafeFieldValue("string", "forename", null, null)() - test_getSafeFieldValue("bool", "isalive", null, null)() - test_getSafeFieldValue("datetime", "created", null, null)() - test_getSafeFieldValue("number", "age", null, null)() - test_getSafeFieldValue("array", "tags", null, [])() - test_getSafeFieldValue("reference", "moretags", null, nothingReference)() - test_getSafeFieldValue("file", "moretags", null, nothingFile)() - }) - - it("bool should parse a defined set of true/false aliases", () => { - test_getSafeFieldValue("bool", "isalive", true, true)() - test_getSafeFieldValue("bool", "isalive", "true", true)() - test_getSafeFieldValue("bool", "isalive", "on", true)() - test_getSafeFieldValue("bool", "isalive", "1", true)() - test_getSafeFieldValue("bool", "isalive", "yes", true)() - test_getSafeFieldValue("bool", "isalive", false, false)() - test_getSafeFieldValue("bool", "isalive", "false", false)() - test_getSafeFieldValue("bool", "isalive", "off", false)() - test_getSafeFieldValue("bool", "isalive", "0", false)() - test_getSafeFieldValue("bool", "isalive", "no", false)() - }) - - it( - "bool should parse invalid values as null", - test_getSafeFieldValue("bool", "isalive", "blah", null) - ) - - it("number should parse numbers and strings that are numbers", () => { - test_getSafeFieldValue("number", "age", 204, 204)() - test_getSafeFieldValue("number", "age", "1", 1)() - test_getSafeFieldValue("number", "age", "45", 45)() - test_getSafeFieldValue("number", "age", "4.11", 4.11)() - }) - - it( - "number should parse invalid values as null", - test_getSafeFieldValue("number", "age", "blah", null) - ) - - it( - "string should parse strings", - test_getSafeFieldValue("string", "forename", "bob", "bob") - ) - - it("string should parse any other basic type", () => { - test_getSafeFieldValue("string", "forename", true, "true")() - test_getSafeFieldValue("string", "forename", 1, "1")() - }) - - it("date should parse dates in various precisions", () => { - // dont forget that JS Date's month is zero based - test_getSafeFieldValue( - "datetime", - "createddate", - "2018-02-14", - new Date(2018, 1, 14) - )() - test_getSafeFieldValue( - "datetime", - "createddate", - "2018-2-14", - new Date(2018, 1, 14) - )() - test_getSafeFieldValue( - "datetime", - "createddate", - "2018-02-14 11:00:00.000", - new Date(2018, 1, 14, 11) - )() - test_getSafeFieldValue( - "datetime", - "createddate", - "2018-02-14 11:30", - new Date(2018, 1, 14, 11, 30) - )() - }) - - it("date should parse invalid dates as null", () => { - // dont forget that JS Date's month is zero based - test_getSafeFieldValue("datetime", "createddate", "2018-13-14", null)() - test_getSafeFieldValue("datetime", "createddate", "2018-2-33", null)() - test_getSafeFieldValue("datetime", "createddate", "bla", null)() - }) - - it("array should parse array", () => { - test_getSafeFieldValue( - "array", - "tags", - ["bob", "the", "dog"], - ["bob", "the", "dog"] - )() - test_getSafeFieldValue( - "array", - "tags", - [true, false], - [true, false] - )() - test_getSafeFieldValue( - "array", - "tags", - [1, 2, 3, 4], - [1, 2, 3, 4] - )() - test_getSafeFieldValue( - "array", - "tags", - [{ key: "/customer/1234", value: "bob" }], - [{ key: "/customer/1234", value: "bob" }] - )() - }) - - it("array should convert the generic's child type", () => { - test_getSafeFieldValue("array", "tags", [1, true], ["1", "true"])() - test_getSafeFieldValue( - "array", - "tags", - ["yes", "true", "no", "false", true, false], - [true, true, false, false, true, false] - )() - test_getSafeFieldValue("array", "tags", ["1", 23], [1, 23])() - }) - - it("reference should parse reference", () => { - test_getSafeFieldValue( - "reference", - "customer", - { key: "/customer/1234", value: "bob" }, - { key: "/customer/1234", value: "bob" } - )() - }) - - it("reference should parse reference", () => { - test_getSafeFieldValue( - "file", - "profilepic", - { relativePath: "path/to/pic.jpg", size: 120 }, - { relativePath: "path/to/pic.jpg", size: 120 } - )() - }) -}) diff --git a/packages/common/test/testSchema.js b/packages/common/test/testSchema.js deleted file mode 100644 index a91bb835ee..0000000000 --- a/packages/common/test/testSchema.js +++ /dev/null @@ -1,38 +0,0 @@ -import { newModel } from "../src/schema/models" -import { newView } from "../src/schema/views" -import { getNewField } from "../src/schema/fields" -import { fullSchema } from "../src/schema/fullSchema" -import { commonRecordValidationRules } from "../src/records/recordValidationRules" - -export function testSchema() { - const addFieldToModel = (model, { type, name }) => { - const field = getNewField(type || "string") - field.name = name - model.fields.push(field) - } - - const contactModel = newModel() - contactModel.name = "Contact" - contactModel.primaryField = "Name" - - addFieldToModel(contactModel, { name: "Name" }) - addFieldToModel(contactModel, { name: "Is Active", type: "bool" }) - addFieldToModel(contactModel, { name: "Created", type: "datetime" }) - addFieldToModel(contactModel, { name: "Status", type: "string" }) - - contactModel.validationRules.push( - commonRecordValidationRules.fieldNotEmpty("Name") - ) - - const activeContactsView = newView(contactModel.id) - activeContactsView.name = "Active Contacts" - activeContactsView.map = "if (doc['Is Active']) emit(doc.Name, doc)" - - const dealModel = newModel() - dealModel.name = "Deal" - addFieldToModel(dealModel, { name: "Name" }) - addFieldToModel(dealModel, { name: "Estimated Value", type: "number" }) - addFieldToModel(dealModel, { name: "Contact", type: "link" }) - - return fullSchema([contactModel, dealModel], [activeContactsView]) -} diff --git a/packages/common/test/types.spec.js b/packages/common/test/types.spec.js new file mode 100644 index 0000000000..ca4db5d447 --- /dev/null +++ b/packages/common/test/types.spec.js @@ -0,0 +1,240 @@ +import { newField, fieldsToSchema, schemaToFields } from "../src/schema/types" + +describe("fields to JSON schema", () => { + + it("should convert text field to string", () => { + + const field = newField("surname", "text") + const schema = fieldsToSchema([field]) + + expect(schema.properties.surname.type).toBe("string") + expect(schema.properties.surname.format).toBeUndefined() + expect(schema.properties.surname.default).toBe("") + }) + + it("should add required field", () => { + + const field = newField("surname", "text") + let schema = fieldsToSchema([field]) + expect(schema.required).toEqual([]) + + field.required = true + schema = fieldsToSchema([field]) + + expect(schema.required).toEqual(["surname"]) + }) + + it("should convert boolean field to boolean", () => { + + const field = newField("active", "boolean") + const schema = fieldsToSchema([field]) + + expect(schema.properties.active.type).toBe("boolean") + expect(schema.properties.active.default).toBe(false) + }) + + it("should convert datetime field to formatted string", () => { + + const field = newField("surname", "datetime") + const schema = fieldsToSchema([field]) + + const datetimeCondition = schema.properties.surname.anyOf.find(s => s.type === "string" && s.format === "date-time") + expect(datetimeCondition).toBeDefined() + + const blankCondition = schema.properties.surname.anyOf.find(s => s.const === "") + expect(blankCondition).toBeDefined() + + expect(schema.properties.surname.default).toBe("") + + }) + + it("should convert link field to object", () => { + + const field = newField("contact", "link") + field.modelId = "1234" + field.viewId = "5678" + const schema = fieldsToSchema([field]) + + expect(schema.properties.contact.type).toBe("object") + expect(schema.properties.contact.required).toEqual(["_id"]) + expect(schema.properties.contact.default).toEqual({ _id: "" }) + expect(schema.properties.contact.properties).toEqual({ + _id: { type: "string" }, + modelId: { const: "1234" }, + viewId: { const: "5678" }, + }) + }) + + it("should convert number field to number", () => { + + const field = newField("age", "number") + field.maximum = 1234 + field.minimum = -5678 + const schema = fieldsToSchema([field]) + + expect(schema.properties).toEqual({ + age: { type: "number", maximum: 1234, minimum: -5678} + }) + }) + + it("should convert select to text with enum", () => { + + const field = newField("status", "select") + field.enum = ["new", "complete"] + const schema = fieldsToSchema([field]) + + expect(schema.properties).toEqual({ + status: { + type: "string", + enum: ["new", "complete"], + default: "", + } + }) + }) +}) + +describe("JSON Schema to fields", () => { + + it("should convert unformatted string to text", () => { + const schema = schemaWithProperty("name", + { + type: "string", + maxLength: 100, + minLength: 4, + }) + const fields = schemaToFields(schema) + + expect(fields).toEqual([ + { + name: "name", + type: "text", + maxLength: 100, + minLength: 4, + required: false, + } + ]) + }) + + it("should convert date-time formatted string to datetime", () => { + const schema = schemaWithProperty("createdDate", + { + anyOf: [ + { + type: "string", + format: "date-time", + }, + { const: "" }, + ] + }) + const fields = schemaToFields(schema) + + expect(fields).toEqual([ + { + name: "createdDate", + type: "datetime", + required: false, + } + ]) + }) + + it("should convert number to number", () => { + const schema = schemaWithProperty("age", + { + type: "number", + maximum: 100, + minimum: 3, + }) + const fields = schemaToFields(schema) + + expect(fields).toEqual([ + { + name: "age", + type: "number", + required: false, + maximum: 100, + minimum: 3, + } + ]) + }) + + it("should convert string with enum to select", () => { + const schema = schemaWithProperty("status", + { + type: "string", + enum: ["new", "complete"] + }) + const fields = schemaToFields(schema) + + expect(fields).toEqual([ + { + name: "status", + type: "select", + required: false, + enum: ["new", "complete"], + } + ]) + }) + + it("should convert boolean to boolean", () => { + const schema = schemaWithProperty("active", + { + type: "boolean", + }) + const fields = schemaToFields(schema) + + expect(fields).toEqual([ + { + name: "active", + type: "boolean", + required: false, + } + ]) + }) + + it("should convert object with modelId & viewId to link", () => { + const schema = schemaWithProperty("contact", + { + type: "object", + properties: { + _id: { type: "string" }, + modelId: { const: "1234" }, + viewId: { const: null }, + } + }) + const fields = schemaToFields(schema) + + expect(fields).toEqual([ + { + name: "contact", + type: "link", + required: false, + modelId: "1234", + viewId: null, + } + ]) + }) + + it("should flag required field", () => { + const schema = schemaWithProperty("name", + { + type: "string", + maxLength: 100, + minLength: 4, + }) + schema.required = ["name"] + const fields = schemaToFields(schema) + + expect(fields[0].required).toBe(true) + }) + + function schemaWithProperty(name, prop) { + const schema = { + type: "object", + properties: {}, + required: [], + } + schema.properties[name] = prop + return schema + } + +}) \ No newline at end of file diff --git a/packages/server/middleware/controllers/record.js b/packages/server/middleware/controllers/record.js index c85f3da950..328341b760 100644 --- a/packages/server/middleware/controllers/record.js +++ b/packages/server/middleware/controllers/record.js @@ -1,22 +1,17 @@ const couchdb = require("../../db") -const { - events, - schemaValidator -} = require("../../../common"); +const { schemaValidator } = require("@budibase/common") exports.save = async function(ctx) { const db = new CouchDB(ctx.params.instanceId); const record = ctx.request.body; // validation with ajv - const model = await db.get(ctx.params.modelId); - const validate = schemaValidator.compile({ - properties: model.schema - }); - const valid = validate(record); + const model = await db.get(record.modelId) + const validate = schemaValidator.compile(model.schema) + const valid = validate(record) if (!valid) { - ctx.status = 400; + ctx.status = 400 ctx.body = { status: 400, errors: validate.errors @@ -33,24 +28,19 @@ exports.save = async function(ctx) { status: 200, record: response } - return; + return } - const response = await db.post({ - modelId: ctx.params.modelId, - type: "record", - ...record - }) - + record.type = "record" + const response = await db.post(record) + record._rev = response.rev // await ctx.publish(events.recordApi.save.onRecordCreated, { // record: record, // }) - ctx.body = { - message: "Record created successfully.", - status: 200, - record: response - }; + ctx.body = record + ctx.status = 200 + ctx.message = `${model.name} ${record._rev ? "updated" : "created"} successfully` } exports.fetch = async function(ctx) { @@ -65,16 +55,12 @@ exports.fetch = async function(ctx) { } exports.find = async function(ctx) { - const db = couchdb.db.use(ctx.params.databaseId) - - const record = await db.get(ctx.params.recordId); - - ctx.body = record; - ctx.status = 200; + const db = couchdb.db.use(ctx.params.instanceId) + ctx.body = await db.get(ctx.params.recordId) } exports.destroy = async function(ctx) { const databaseId = ctx.params.instanceId; const db = new CouchDB(databaseId) ctx.body = await db.destroy(ctx.params.recordId, ctx.params.revId); -}; \ No newline at end of file +}; diff --git a/packages/server/middleware/routers.js b/packages/server/middleware/routers.js index 934b655474..2e5c5fed0b 100644 --- a/packages/server/middleware/routers.js +++ b/packages/server/middleware/routers.js @@ -137,7 +137,7 @@ module.exports = (config, app) => { await next(); } catch (err) { console.trace(err); - ctx.status = err.status || 500; + ctx.status = err.status || err.statusCode || 500; ctx.body = { message: err.message, status: ctx.status diff --git a/packages/server/middleware/routes/neo/record.js b/packages/server/middleware/routes/neo/record.js index e571c0927d..998edae9a5 100644 --- a/packages/server/middleware/routes/neo/record.js +++ b/packages/server/middleware/routes/neo/record.js @@ -1,12 +1,12 @@ -const Router = require("@koa/router"); -const controller = require("../../controllers/record"); +const Router = require("@koa/router") +const controller = require("../../controllers/record") -const router = Router(); +const router = Router() router - .get("/api/:instanceId/:viewName/records", controller.fetch) + .get("/api/:instanceId/:modelId/records", controller.fetch) .get("/api/:instanceId/records/:recordId", controller.find) - .post("/api/:instanceId/:modelId/records", controller.save) - .delete("/api/:instanceId/records/:recordId/:revId", controller.destroy); + .post("/api/:instanceId/records", controller.save) + .delete("/api/:instanceId/records/:recordId/:revId", controller.destroy) -module.exports = router; \ No newline at end of file +module.exports = router diff --git a/packages/server/middleware/routes/neo/tests/couchTestUtils.js b/packages/server/middleware/routes/neo/tests/couchTestUtils.js index 0491b363c7..cf2f5803b1 100644 --- a/packages/server/middleware/routes/neo/tests/couchTestUtils.js +++ b/packages/server/middleware/routes/neo/tests/couchTestUtils.js @@ -5,8 +5,8 @@ const TEST_APP_ID = "test-app"; exports.destroyDatabase = couchdb.db.destroy; -exports.createModel = async instanceId => { - const model = { +exports.createModel = async (instanceId, model) => { + model = model || { "name": "TestModel", "type": "model", "key": "name", @@ -21,9 +21,11 @@ exports.createModel = async instanceId => { designDoc.views = { ...designDoc.views, [`all_${response.id}`]: { - map: function(doc) { - emit([doc.modelId], doc._id); - } + map: `function(doc) { + if (doc.modelId === "${response.id}") { + emit(doc[doc.key], doc._id); + } + }` } }; await db.insert(designDoc, designDoc._id); @@ -85,4 +87,13 @@ exports.createInstanceDatabase = async instanceId => { exports.insertDocument = async (databaseId, document) => { const { id, ...documentFields } = document; await couchdb.db.use(databaseId).insert(documentFields, id); -} \ No newline at end of file +} + +exports.createSchema = async (request, instanceId, schema) => { + for (let model of schema.models) { + await request.post(`/api/${instanceId}/models`).send(model) + } + for (let view of schema.views) { + await request.post(`/api/${instanceId}/views`).send(view) + } +} diff --git a/packages/server/middleware/routes/neo/tests/record.spec.js b/packages/server/middleware/routes/neo/tests/record.spec.js new file mode 100644 index 0000000000..c0cd62d056 --- /dev/null +++ b/packages/server/middleware/routes/neo/tests/record.spec.js @@ -0,0 +1,124 @@ +const supertest = require("supertest"); +const app = require("../../../../app"); +const { createInstanceDatabase, createModel, destroyDatabase } = require("./couchTestUtils"); +const { getNewRecord } = require("../../../../../common/lib/records/getNewRecord") +const { testSchema } = require("../../../../../common/lib/testUtils/testSchema") + +const TEST_INSTANCE_ID = "testing-123"; + +describe("/records", () => { + let request; + let server; + + beforeAll(async () => { + server = await app({ + config: { + port: 3000 + } + }); + request = supertest(server); + }); + + afterAll(async () => { + server.close(); + }) + + describe("save, load, update, delete", () => { + const schema = testSchema() + + beforeAll(async () => { + await createInstanceDatabase(TEST_INSTANCE_ID); + await createModel(TEST_INSTANCE_ID, schema.findModel("Contact")) + }); + + afterAll(async () => { + await destroyDatabase(TEST_INSTANCE_ID); + }); + + let record = getNewRecord(schema, "Contact") + record.name = "Test Contact" + record.Status = "new" + + it("returns a success message when the record is created", done => { + request + .post(`/api/${TEST_INSTANCE_ID}/records`) + .send(record) + .set("Accept", "application/json") + .expect('Content-Type', /json/) + .expect(200) + .end(async (err, res) => { + expect(res.res.statusMessage.toLowerCase()).toEqual("contact created successfully") + expect(res.body.name).toEqual("Test Contact") + expect(res.body._rev).toBeDefined() + record = res.body + done(); + }); + }) + + it("updates a record successfully", async () => { + record.name = "Updated Name" + const res = await request + .post(`/api/${TEST_INSTANCE_ID}/records`) + .send(record) + .set("Accept", "application/json") + .expect('Content-Type', /json/) + .expect(200) + + expect(res.res.statusMessage.toLowerCase()).toEqual("contact updated successfully") + expect(res.body.name).toEqual("Updated Name") + record = res.body + }) + + it("should load a record", async () => { + const res = await request + .get(`/api/${TEST_INSTANCE_ID}/records/${record._id}`) + .set("Accept", "application/json") + .expect('Content-Type', /json/) + .expect(200) + expect(res.body).toEqual(record) + }) + + it("should list all records for given modelId", async () => { + const secondRecord = getNewRecord(schema, "Contact") + secondRecord.name = "Second Contact" + secondRecord.Status = "new" + + await request + .post(`/api/${TEST_INSTANCE_ID}/records`) + .send(secondRecord) + .set("Accept", "application/json") + + const res = await request + .get(`/api/${TEST_INSTANCE_ID}/${record.modelId}/records`) + .set("Accept", "application/json") + .expect('Content-Type', /json/) + .expect(200) + + expect(res.body.length).toBe(2) + console.log(JSON.stringify(res.body, undefined, 2)) + expect(res.body.find(c => c.name === record.name)).toBeDefined() + expect(res.body.find(c => c.name === secondRecord.name)).toBeDefined() + }) + + it("should return 404 when load, after a delete", async () => { + await request + .delete(`/api/${TEST_INSTANCE_ID}/records/${record._id}/${record._rev}`) + .expect(200) + + await request + .get(`/api/${TEST_INSTANCE_ID}/records/${record._id}`) + .set("Accept", "application/json") + .expect('Content-Type', /json/) + .expect(404) + }) + + it("load should return 404 when record does not exist", async () => { + await request + .get(`/api/${TEST_INSTANCE_ID}/records/not-a-valid-id`) + .set("Accept", "application/json") + .expect('Content-Type', /json/) + .expect(404) + }) + + }) +})