@webiny/api-apw 5.37.0-beta.0 → 5.37.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ApwChangeRequestNotification.js.map +1 -1
- package/ApwCommentNotification.js.map +1 -1
- package/ApwContentReviewNotification.js.map +1 -1
- package/ApwContentUrlPlugin.js.map +1 -1
- package/ContentApwSettingsPlugin.js.map +1 -1
- package/crud/createChangeRequestMethods.js.map +1 -1
- package/crud/createCommentMethods.js.map +1 -1
- package/crud/createContentReviewMethods.js +20 -5
- package/crud/createContentReviewMethods.js.map +1 -1
- package/crud/createReviewerMethods.js.map +1 -1
- package/crud/createWorkflowMethods.js.map +1 -1
- package/crud/index.js.map +1 -1
- package/crud/utils.js.map +1 -1
- package/index.js.map +1 -1
- package/package.json +32 -37
- package/plugins/cms/CmsEntryApwSettingsGetterPlugin.js.map +1 -1
- package/plugins/cms/apwEntryPlugins.js.map +1 -1
- package/plugins/cms/index.js.map +1 -1
- package/plugins/cms/linkContentReviewToEntry.js +2 -2
- package/plugins/cms/linkContentReviewToEntry.js.map +1 -1
- package/plugins/cms/linkWorkflowToEntry.js +7 -7
- package/plugins/cms/linkWorkflowToEntry.js.map +1 -1
- package/plugins/cms/notifications/changeRequestNotification.js.map +1 -1
- package/plugins/cms/notifications/commentNotification.js.map +1 -1
- package/plugins/cms/notifications/contentReviewNotification.js.map +1 -1
- package/plugins/cms/notifications/contentUrl.js.map +1 -1
- package/plugins/cms/triggerContentReview.js +3 -3
- package/plugins/cms/triggerContentReview.js.map +1 -1
- package/plugins/cms/updateContentReviewStatus.js +4 -4
- package/plugins/cms/updateContentReviewStatus.js.map +1 -1
- package/plugins/cms/utils.js.map +1 -1
- package/plugins/context.js.map +1 -1
- package/plugins/graphql/changeRequest.gql.js.map +1 -1
- package/plugins/graphql/comment.gql.js.map +1 -1
- package/plugins/graphql/contentReview.gql.js.map +1 -1
- package/plugins/graphql/reviewer.gql.js.map +1 -1
- package/plugins/graphql/workflow.gql.js.map +1 -1
- package/plugins/graphql.js.map +1 -1
- package/plugins/hooks/createReviewerFromIdentity.js.map +1 -1
- package/plugins/hooks/deleteChangeRequestsAfterContentReview.js.map +1 -1
- package/plugins/hooks/deleteCommentsAfterChangeRequest.js.map +1 -1
- package/plugins/hooks/index.js.map +1 -1
- package/plugins/hooks/initializeContentReviewSteps.js.map +1 -1
- package/plugins/hooks/initializeNotifications.js.map +1 -1
- package/plugins/hooks/listContentReviews.js.map +1 -1
- package/plugins/hooks/notifications/appUrl.js.map +1 -1
- package/plugins/hooks/notifications/changeRequestAfterCreate.js.map +1 -1
- package/plugins/hooks/notifications/changeRequestUrl.js.map +1 -1
- package/plugins/hooks/notifications/commentAfterCreate.js.map +1 -1
- package/plugins/hooks/notifications/commentUrl.js.map +1 -1
- package/plugins/hooks/notifications/contentReviewAfterCreate.js.map +1 -1
- package/plugins/hooks/notifications/contentReviewUrl.js.map +1 -1
- package/plugins/hooks/notifications/contentUrl.js.map +1 -1
- package/plugins/hooks/notifications/lastChangeRequestNotificationPlugin.js.map +1 -1
- package/plugins/hooks/notifications/lastCommentNotificationPlugin.js.map +1 -1
- package/plugins/hooks/notifications/lastContentReviewNotificationPlugin.js.map +1 -1
- package/plugins/hooks/notifications/reviewers.js.map +1 -1
- package/plugins/hooks/notifications/sendChangeRequestNotification.js.map +1 -1
- package/plugins/hooks/notifications/sendCommentNotification.js.map +1 -1
- package/plugins/hooks/notifications/sendContentReviewNotification.js.map +1 -1
- package/plugins/hooks/updatePendingChangeRequests.js.map +1 -1
- package/plugins/hooks/updateTotalComments.js.map +1 -1
- package/plugins/hooks/validateChangeRequest.js.map +1 -1
- package/plugins/hooks/validateComment.js.map +1 -1
- package/plugins/hooks/validateContentReview.js.map +1 -1
- package/plugins/pageBuilder/PageApwSettingsGetterPlugin.js.map +1 -1
- package/plugins/pageBuilder/apwContentPagePlugins.js.map +1 -1
- package/plugins/pageBuilder/extendPbPageSettingsSchema.js.map +1 -1
- package/plugins/pageBuilder/index.js.map +1 -1
- package/plugins/pageBuilder/linkContentReviewToPage.js +2 -2
- package/plugins/pageBuilder/linkContentReviewToPage.js.map +1 -1
- package/plugins/pageBuilder/linkWorkflowToPage.js.map +1 -1
- package/plugins/pageBuilder/notifications/changeRequestNotification.js.map +1 -1
- package/plugins/pageBuilder/notifications/commentNotification.js.map +1 -1
- package/plugins/pageBuilder/notifications/contentReviewNotification.js.map +1 -1
- package/plugins/pageBuilder/notifications/contentUrl.js.map +1 -1
- package/plugins/pageBuilder/triggerContentReview.js.map +1 -1
- package/plugins/pageBuilder/updateContentReviewStatus.js.map +1 -1
- package/plugins/pageBuilder/utils.js.map +1 -1
- package/plugins/utils.js.map +1 -1
- package/scheduler/createScheduleActionMethods.js.map +1 -1
- package/scheduler/handlers/executeAction/index.js +2 -2
- package/scheduler/handlers/executeAction/index.js.map +1 -1
- package/scheduler/handlers/executeAction/plugins/ApplicationGraphQL.js.map +1 -1
- package/scheduler/handlers/executeAction/plugins/HeadlessCMSGraphQL.js.map +1 -1
- package/scheduler/handlers/executeAction/plugins/PageBuilderGraphQL.js.map +1 -1
- package/scheduler/handlers/executeAction/security.js.map +1 -1
- package/scheduler/handlers/scheduleAction/index.js +4 -4
- package/scheduler/handlers/scheduleAction/index.js.map +1 -1
- package/scheduler/handlers/scheduleAction/scheduleAction.utils.js.map +1 -1
- package/scheduler/handlers/utils.js.map +1 -1
- package/scheduler/index.js.map +1 -1
- package/scheduler/types.js +12 -12
- package/scheduler/types.js.map +1 -1
- package/storageOperations/changeRequestStorageOperations.js.map +1 -1
- package/storageOperations/commentStorageOperations.js.map +1 -1
- package/storageOperations/contentReviewStorageOperations.js.map +1 -1
- package/storageOperations/index.js.map +1 -1
- package/storageOperations/models/changeRequest.model.js.map +1 -1
- package/storageOperations/models/comment.model.js.map +1 -1
- package/storageOperations/models/contentModelPluginFactory.js.map +1 -1
- package/storageOperations/models/contentReview.model.js.map +1 -1
- package/storageOperations/models/index.js.map +1 -1
- package/storageOperations/models/reviewer.model.js.map +1 -1
- package/storageOperations/models/utils.js.map +1 -1
- package/storageOperations/models/workflow.model.js.map +1 -1
- package/storageOperations/reviewerStorageOperations.js.map +1 -1
- package/storageOperations/workflowStorageOperations.js.map +1 -1
- package/types.js +124 -28
- package/types.js.map +1 -1
- package/utils/contentApwSettingsPlugin.js.map +1 -1
- package/utils/errors.js.map +1 -1
- package/utils/fieldResolver.js.map +1 -1
- package/utils/resolve.js.map +1 -1
package/plugins/utils.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["hasReviewer","params","getReviewer","identity","step","stepReviewer","reviewers","entry","id","identityId","getValue","object","key","get","getContentReviewStepInitialStatus","workflowSteps","index","previousStepStatus","ApwContentReviewStepStatus","ACTIVE","previousStep","type","ApwWorkflowStepTypes","MANDATORY_BLOCKING","INACTIVE","getNextStepStatus","previousStepType","DONE","extractContentReviewIdAndStep","entryId","version","stepId","split","revisionId","safelyGetContentReview","contentReviewMethods","contentReviewEntry","e","message","code","updateContentReview","getNewContentReviewData","newContentReviewData","update","updateContentReviewStep","steps","updater","map","isInstallationPending","tenancy","i18n","tenant","getCurrentTenant","getContentLocale","WORKFLOW_PRECEDENCE","WorkflowScopeTypes","DEFAULT","CUSTOM","workflowByPrecedenceDesc","a","b","scoreA","scope","scoreB","workflowByCreatedOnDesc","createdOnA","createdOnB","Date","getTime"],"sources":["utils.ts"],"sourcesContent":["import get from \"lodash/get\";\nimport { CmsModelField } from \"@webiny/api-headless-cms/types\";\nimport { SecurityIdentity } from \"@webiny/api-security/types\";\nimport {\n ApwChangeRequest,\n ApwContentReview,\n ApwContentReviewCrud,\n ApwContentReviewStep,\n ApwContentReviewStepStatus,\n ApwContext,\n ApwReviewerCrud,\n ApwWorkflow,\n ApwWorkflowStep,\n ApwWorkflowStepTypes,\n WorkflowScopeTypes\n} from \"~/types\";\n\nexport interface CreateModelFieldParams\n extends Omit<CmsModelField, \"id\" | \"storageId\" | \"fieldId\"> {\n fieldId?: string;\n parent: string;\n}\n\nexport interface HasReviewersParams {\n identity: SecurityIdentity;\n step: ApwContentReviewStep;\n getReviewer: ApwReviewerCrud[\"get\"];\n}\n\nexport const hasReviewer = async (params: HasReviewersParams): Promise<Boolean> => {\n const { getReviewer, identity, step } = params;\n for (const stepReviewer of step.reviewers) {\n const entry = await getReviewer(stepReviewer.id);\n\n if (entry.identityId === identity.id) {\n return true;\n }\n }\n\n return false;\n};\n\nexport const getValue = (object: Record<string, any>, key: string) => {\n return get(object, `values.${key}`);\n};\n\nexport const getContentReviewStepInitialStatus = (\n workflowSteps: ApwWorkflowStep[],\n index: number,\n previousStepStatus?: ApwContentReviewStepStatus\n): ApwContentReviewStepStatus => {\n /**\n * Always set first step 'active' by default.\n */\n if (index === 0) {\n return ApwContentReviewStepStatus.ACTIVE;\n }\n\n const previousStep = workflowSteps[index - 1];\n if (\n previousStepStatus === ApwContentReviewStepStatus.ACTIVE &&\n previousStep.type !== ApwWorkflowStepTypes.MANDATORY_BLOCKING\n ) {\n return ApwContentReviewStepStatus.ACTIVE;\n }\n\n return ApwContentReviewStepStatus.INACTIVE;\n};\n\nexport const getNextStepStatus = (\n previousStepType: ApwWorkflowStepTypes,\n previousStepStatus: ApwContentReviewStepStatus\n): ApwContentReviewStepStatus => {\n if (previousStepStatus === ApwContentReviewStepStatus.DONE) {\n return ApwContentReviewStepStatus.ACTIVE;\n }\n\n if (\n previousStepStatus === ApwContentReviewStepStatus.ACTIVE &&\n previousStepType !== ApwWorkflowStepTypes.MANDATORY_BLOCKING\n ) {\n return ApwContentReviewStepStatus.ACTIVE;\n }\n\n return ApwContentReviewStepStatus.INACTIVE;\n};\n\nexport interface ExtractContentReviewIdAndStepResult {\n id: string;\n stepId: string;\n}\n\nexport const extractContentReviewIdAndStep = (\n step: ApwChangeRequest[\"step\"]\n): ExtractContentReviewIdAndStepResult => {\n /*\n * Get associated content review entry.\n */\n const [entryId, version, stepId] = step.split(\"#\");\n const revisionId = `${entryId}#${version}`;\n\n return {\n id: revisionId,\n stepId\n };\n};\n\ntype SafelyGetContentReviewParams = Pick<UpdateContentReviewParams, \"id\" | \"contentReviewMethods\">;\n\nexport const safelyGetContentReview = async ({\n id,\n contentReviewMethods\n}: SafelyGetContentReviewParams): Promise<ApwContentReview | null> => {\n let contentReviewEntry = null;\n try {\n contentReviewEntry = await contentReviewMethods.get(id);\n } catch (e) {\n if (e.message !== \"index_not_found_exception\" && e.code !== \"NOT_FOUND\") {\n throw e;\n }\n }\n\n return contentReviewEntry;\n};\n\nexport interface UpdateContentReviewParams {\n id: string;\n contentReviewMethods: ApwContentReviewCrud;\n getNewContentReviewData: (entry: ApwContentReview) => ApwContentReview;\n}\n\nexport const updateContentReview = async ({\n contentReviewMethods,\n id,\n getNewContentReviewData\n}: UpdateContentReviewParams): Promise<void> => {\n const contentReviewEntry = await safelyGetContentReview({ id, contentReviewMethods });\n if (contentReviewEntry) {\n const newContentReviewData = getNewContentReviewData(contentReviewEntry);\n /**\n * Update content review entry.\n */\n await contentReviewMethods.update(contentReviewEntry.id, newContentReviewData);\n }\n};\n\nexport const updateContentReviewStep = (\n steps: ApwContentReviewStep[],\n stepId: string,\n updater: (step: ApwContentReviewStep) => ApwContentReviewStep\n): ApwContentReviewStep[] => {\n return steps.map(step => {\n if (step.id === stepId) {\n return {\n ...updater(step)\n };\n }\n return step;\n });\n};\n\ntype CheckInstallationParams = Pick<ApwContext, \"tenancy\" | \"i18n\">;\n\nexport const isInstallationPending = ({ tenancy, i18n }: CheckInstallationParams): boolean => {\n /**\n * In case of a fresh webiny project \"tenant\" and \"locale\" won't be there until\n * installation is completed. So, we need to skip \"APW\" creation till then.\n */\n const tenant = tenancy.getCurrentTenant();\n if (!tenant) {\n return true;\n }\n\n return !i18n.getContentLocale();\n};\n\nconst WORKFLOW_PRECEDENCE = {\n [WorkflowScopeTypes.DEFAULT]: 0,\n [WorkflowScopeTypes.CUSTOM]: 1\n};\n\nexport const workflowByPrecedenceDesc = (a: ApwWorkflow, b: ApwWorkflow) => {\n const scoreA = WORKFLOW_PRECEDENCE[a.scope.type];\n const scoreB = WORKFLOW_PRECEDENCE[b.scope.type];\n /**\n * In descending order of workflow precedence.\n */\n return scoreB - scoreA;\n};\n\nexport const workflowByCreatedOnDesc = (a: ApwWorkflow, b: ApwWorkflow) => {\n const createdOnA = get(a, \"createdOn\");\n const createdOnB = get(b, \"createdOn\");\n /**\n * In descending order of workflow createdOn i.e. the most recent one first.\n */\n return new Date(createdOnB).getTime() - new Date(createdOnA).getTime();\n};\n"],"mappings":";;;;;;;;AAAA;AAGA;AA0BO,MAAMA,WAAW,GAAG,MAAOC,MAA0B,IAAuB;EAC/E,MAAM;IAAEC,WAAW;IAAEC,QAAQ;IAAEC;EAAK,CAAC,GAAGH,MAAM;EAC9C,KAAK,MAAMI,YAAY,IAAID,IAAI,CAACE,SAAS,EAAE;IACvC,MAAMC,KAAK,GAAG,MAAML,WAAW,CAACG,YAAY,CAACG,EAAE,CAAC;IAEhD,IAAID,KAAK,CAACE,UAAU,KAAKN,QAAQ,CAACK,EAAE,EAAE;MAClC,OAAO,IAAI;IACf;EACJ;EAEA,OAAO,KAAK;AAChB,CAAC;AAAC;AAEK,MAAME,QAAQ,GAAG,CAACC,MAA2B,EAAEC,GAAW,KAAK;EAClE,OAAO,IAAAC,YAAG,EAACF,MAAM,EAAG,UAASC,GAAI,EAAC,CAAC;AACvC,CAAC;AAAC;AAEK,MAAME,iCAAiC,GAAG,CAC7CC,aAAgC,EAChCC,KAAa,EACbC,kBAA+C,KAClB;EAC7B;AACJ;AACA;EACI,IAAID,KAAK,KAAK,CAAC,EAAE;IACb,OAAOE,iCAA0B,CAACC,MAAM;EAC5C;EAEA,MAAMC,YAAY,GAAGL,aAAa,CAACC,KAAK,GAAG,CAAC,CAAC;EAC7C,IACIC,kBAAkB,KAAKC,iCAA0B,CAACC,MAAM,IACxDC,YAAY,CAACC,IAAI,KAAKC,2BAAoB,CAACC,kBAAkB,EAC/D;IACE,OA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CAAC;AAAC;AAEK,MAAMG,uBAAuB,GAAG,CAACL,CAAc,EAAEC,CAAc,KAAK;EACvE,MAAMK,UAAU,GAAG,IAAApD,YAAG,EAAC8C,CAAC,EAAE,WAAW,CAAC;EACtC,MAAMO,UAAU,GAAG,IAAArD,YAAG,EAAC+C,CAAC,EAAE,WAAW,CAAC;EACtC;AACJ;AACA;EACI,OAAO,IAAIO,IAAI,CAACD,UAAU,CAAC,CAACE,OAAO,EAAE,GAAG,IAAID,IAAI,CAACF,UAAU,CAAC,CAACG,OAAO,EAAE;AAC1E,CAAC;AAAC"}
|
1
|
+
{"version":3,"names":["_get","_interopRequireDefault","require","_types","hasReviewer","params","getReviewer","identity","step","stepReviewer","reviewers","entry","id","identityId","exports","getValue","object","key","get","getContentReviewStepInitialStatus","workflowSteps","index","previousStepStatus","ApwContentReviewStepStatus","ACTIVE","previousStep","type","ApwWorkflowStepTypes","MANDATORY_BLOCKING","INACTIVE","getNextStepStatus","previousStepType","DONE","extractContentReviewIdAndStep","entryId","version","stepId","split","revisionId","safelyGetContentReview","contentReviewMethods","contentReviewEntry","e","message","code","updateContentReview","getNewContentReviewData","newContentReviewData","update","updateContentReviewStep","steps","updater","map","_objectSpread2","default","isInstallationPending","tenancy","i18n","tenant","getCurrentTenant","getContentLocale","WORKFLOW_PRECEDENCE","WorkflowScopeTypes","DEFAULT","CUSTOM","workflowByPrecedenceDesc","a","b","scoreA","scope","scoreB","workflowByCreatedOnDesc","createdOnA","createdOnB","Date","getTime"],"sources":["utils.ts"],"sourcesContent":["import get from \"lodash/get\";\nimport { CmsModelField } from \"@webiny/api-headless-cms/types\";\nimport { SecurityIdentity } from \"@webiny/api-security/types\";\nimport {\n ApwChangeRequest,\n ApwContentReview,\n ApwContentReviewCrud,\n ApwContentReviewStep,\n ApwContentReviewStepStatus,\n ApwContext,\n ApwReviewerCrud,\n ApwWorkflow,\n ApwWorkflowStep,\n ApwWorkflowStepTypes,\n WorkflowScopeTypes\n} from \"~/types\";\n\nexport interface CreateModelFieldParams\n extends Omit<CmsModelField, \"id\" | \"storageId\" | \"fieldId\"> {\n fieldId?: string;\n parent: string;\n}\n\nexport interface HasReviewersParams {\n identity: SecurityIdentity;\n step: ApwContentReviewStep;\n getReviewer: ApwReviewerCrud[\"get\"];\n}\n\nexport const hasReviewer = async (params: HasReviewersParams): Promise<Boolean> => {\n const { getReviewer, identity, step } = params;\n for (const stepReviewer of step.reviewers) {\n const entry = await getReviewer(stepReviewer.id);\n\n if (entry.identityId === identity.id) {\n return true;\n }\n }\n\n return false;\n};\n\nexport const getValue = (object: Record<string, any>, key: string) => {\n return get(object, `values.${key}`);\n};\n\nexport const getContentReviewStepInitialStatus = (\n workflowSteps: ApwWorkflowStep[],\n index: number,\n previousStepStatus?: ApwContentReviewStepStatus\n): ApwContentReviewStepStatus => {\n /**\n * Always set first step 'active' by default.\n */\n if (index === 0) {\n return ApwContentReviewStepStatus.ACTIVE;\n }\n\n const previousStep = workflowSteps[index - 1];\n if (\n previousStepStatus === ApwContentReviewStepStatus.ACTIVE &&\n previousStep.type !== ApwWorkflowStepTypes.MANDATORY_BLOCKING\n ) {\n return ApwContentReviewStepStatus.ACTIVE;\n }\n\n return ApwContentReviewStepStatus.INACTIVE;\n};\n\nexport const getNextStepStatus = (\n previousStepType: ApwWorkflowStepTypes,\n previousStepStatus: ApwContentReviewStepStatus\n): ApwContentReviewStepStatus => {\n if (previousStepStatus === ApwContentReviewStepStatus.DONE) {\n return ApwContentReviewStepStatus.ACTIVE;\n }\n\n if (\n previousStepStatus === ApwContentReviewStepStatus.ACTIVE &&\n previousStepType !== ApwWorkflowStepTypes.MANDATORY_BLOCKING\n ) {\n return ApwContentReviewStepStatus.ACTIVE;\n }\n\n return ApwContentReviewStepStatus.INACTIVE;\n};\n\nexport interface ExtractContentReviewIdAndStepResult {\n id: string;\n stepId: string;\n}\n\nexport const extractContentReviewIdAndStep = (\n step: ApwChangeRequest[\"step\"]\n): ExtractContentReviewIdAndStepResult => {\n /*\n * Get associated content review entry.\n */\n const [entryId, version, stepId] = step.split(\"#\");\n const revisionId = `${entryId}#${version}`;\n\n return {\n id: revisionId,\n stepId\n };\n};\n\ntype SafelyGetContentReviewParams = Pick<UpdateContentReviewParams, \"id\" | \"contentReviewMethods\">;\n\nexport const safelyGetContentReview = async ({\n id,\n contentReviewMethods\n}: SafelyGetContentReviewParams): Promise<ApwContentReview | null> => {\n let contentReviewEntry = null;\n try {\n contentReviewEntry = await contentReviewMethods.get(id);\n } catch (e) {\n if (e.message !== \"index_not_found_exception\" && e.code !== \"NOT_FOUND\") {\n throw e;\n }\n }\n\n return contentReviewEntry;\n};\n\nexport interface UpdateContentReviewParams {\n id: string;\n contentReviewMethods: ApwContentReviewCrud;\n getNewContentReviewData: (entry: ApwContentReview) => ApwContentReview;\n}\n\nexport const updateContentReview = async ({\n contentReviewMethods,\n id,\n getNewContentReviewData\n}: UpdateContentReviewParams): Promise<void> => {\n const contentReviewEntry = await safelyGetContentReview({ id, contentReviewMethods });\n if (contentReviewEntry) {\n const newContentReviewData = getNewContentReviewData(contentReviewEntry);\n /**\n * Update content review entry.\n */\n await contentReviewMethods.update(contentReviewEntry.id, newContentReviewData);\n }\n};\n\nexport const updateContentReviewStep = (\n steps: ApwContentReviewStep[],\n stepId: string,\n updater: (step: ApwContentReviewStep) => ApwContentReviewStep\n): ApwContentReviewStep[] => {\n return steps.map(step => {\n if (step.id === stepId) {\n return {\n ...updater(step)\n };\n }\n return step;\n });\n};\n\ntype CheckInstallationParams = Pick<ApwContext, \"tenancy\" | \"i18n\">;\n\nexport const isInstallationPending = ({ tenancy, i18n }: CheckInstallationParams): boolean => {\n /**\n * In case of a fresh webiny project \"tenant\" and \"locale\" won't be there until\n * installation is completed. So, we need to skip \"APW\" creation till then.\n */\n const tenant = tenancy.getCurrentTenant();\n if (!tenant) {\n return true;\n }\n\n return !i18n.getContentLocale();\n};\n\nconst WORKFLOW_PRECEDENCE = {\n [WorkflowScopeTypes.DEFAULT]: 0,\n [WorkflowScopeTypes.CUSTOM]: 1\n};\n\nexport const workflowByPrecedenceDesc = (a: ApwWorkflow, b: ApwWorkflow) => {\n const scoreA = WORKFLOW_PRECEDENCE[a.scope.type];\n const scoreB = WORKFLOW_PRECEDENCE[b.scope.type];\n /**\n * In descending order of workflow precedence.\n */\n return scoreB - scoreA;\n};\n\nexport const workflowByCreatedOnDesc = (a: ApwWorkflow, b: ApwWorkflow) => {\n const createdOnA = get(a, \"createdOn\");\n const createdOnB = get(b, \"createdOn\");\n /**\n * In descending order of workflow createdOn i.e. the most recent one first.\n */\n return new Date(createdOnB).getTime() - new Date(createdOnA).getTime();\n};\n"],"mappings":";;;;;;;;AAAA,IAAAA,IAAA,GAAAC,sBAAA,CAAAC,OAAA;AAGA,IAAAC,MAAA,GAAAD,OAAA;AA0BO,MAAME,WAAW,GAAG,MAAOC,MAA0B,IAAuB;EAC/E,MAAM;IAAEC,WAAW;IAAEC,QAAQ;IAAEC;EAAK,CAAC,GAAGH,MAAM;EAC9C,KAAK,MAAMI,YAAY,IAAID,IAAI,CAACE,SAAS,EAAE;IACvC,MAAMC,KAAK,GAAG,MAAML,WAAW,CAACG,YAAY,CAACG,EAAE,CAAC;IAEhD,IAAID,KAAK,CAACE,UAAU,KAAKN,QAAQ,CAACK,EAAE,EAAE;MAClC,OAAO,IAAI;IACf;EACJ;EAEA,OAAO,KAAK;AAChB,CAAC;AAACE,OAAA,CAAAV,WAAA,GAAAA,WAAA;AAEK,MAAMW,QAAQ,GAAGA,CAACC,MAA2B,EAAEC,GAAW,KAAK;EAClE,OAAO,IAAAC,YAAG,EAACF,MAAM,EAAG,UAASC,GAAI,EAAC,CAAC;AACvC,CAAC;AAACH,OAAA,CAAAC,QAAA,GAAAA,QAAA;AAEK,MAAMI,iCAAiC,GAAGA,CAC7CC,aAAgC,EAChCC,KAAa,EACbC,kBAA+C,KAClB;EAC7B;AACJ;AACA;EACI,IAAID,KAAK,KAAK,CAAC,EAAE;IACb,OAAOE,iCAA0B,C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,IAAI;EACf;EAEA,OAAO,CAACD,IAAI,CAACG,gBAAgB,CAAC,CAAC;AACnC,CAAC;AAAC9C,OAAA,CAAAyC,qBAAA,GAAAA,qBAAA;AAEF,MAAMM,mBAAmB,GAAG;EACxB,CAACC,yBAAkB,CAACC,OAAO,GAAG,CAAC;EAC/B,CAACD,yBAAkB,CAACE,MAAM,GAAG;AACjC,CAAC;AAEM,MAAMC,wBAAwB,GAAGA,CAACC,CAAc,EAAEC,CAAc,KAAK;EACxE,MAAMC,MAAM,GAAGP,mBAAmB,CAACK,CAAC,CAACG,KAAK,CAAC3C,IAAI,CAAC;EAChD,MAAM4C,MAAM,GAAGT,mBAAmB,CAACM,CAAC,CAACE,KAAK,CAAC3C,IAAI,CAAC;EAChD;AACJ;AACA;EACI,OAAO4C,MAAM,GAAGF,MAAM;AAC1B,CAAC;AAACtD,OAAA,CAAAmD,wBAAA,GAAAA,wBAAA;AAEK,MAAMM,uBAAuB,GAAGA,CAACL,CAAc,EAAEC,CAAc,KAAK;EACvE,MAAMK,UAAU,GAAG,IAAAtD,YAAG,EAACgD,CAAC,EAAE,WAAW,CAAC;EACtC,MAAMO,UAAU,GAAG,IAAAvD,YAAG,EAACiD,CAAC,EAAE,WAAW,CAAC;EACtC;AACJ;AACA;EACI,OAAO,IAAIO,IAAI,CAACD,UAAU,CAAC,CAACE,OAAO,CAAC,CAAC,GAAG,IAAID,IAAI,CAACF,UAAU,CAAC,CAACG,OAAO,CAAC,CAAC;AAC1E,CAAC;AAAC7D,OAAA,CAAAyD,uBAAA,GAAAA,uBAAA"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["CreateDataModel","withFields","instance","datetime","string","validation","create","type","ApwContentTypes","PAGE","CMS_ENTRY","action","ApwScheduleActionTypes","PUBLISH","UNPUBLISH","entryId","modelId","value","Error","createScheduleActionMethods","storageOperations","getIdentity","getTenant","getLocale","getTenantAndLocale","tenant","id","locale","code","get","where","list","params","input","createDataModel","populate","validate","mdbid","identity","data","toJSON","scheduleAction","createdOn","Date","toISOString","savedOn","createdBy","displayName","item","update","updateDataModel","original","delete","getCurrentTask","updateCurrentTask","deleteCurrentTask"],"sources":["createScheduleActionMethods.ts"],"sourcesContent":["/**\n * Package @commodo/fields does not have types.\n */\n// @ts-ignore\nimport { string, withFields } from \"@commodo/fields\";\nimport { validation } from \"@webiny/validation\";\nimport { mdbid } from \"@webiny/utils\";\nimport {\n ApwContentTypes,\n ApwScheduleAction,\n ApwScheduleActionCrud,\n ApwScheduleActionData,\n ApwScheduleActionTypes,\n CreateScheduleActionParams\n} from \"~/scheduler/types\";\n\nconst CreateDataModel = withFields((instance: any) => {\n return {\n datetime: string({\n validation: validation.create(`required`)\n }),\n type: string({\n validation: validation.create(\n `required,in:${ApwContentTypes.PAGE}:${ApwContentTypes.CMS_ENTRY}`\n )\n }),\n action: string({\n validation: validation.create(\n `required,in:${ApwScheduleActionTypes.PUBLISH}:${ApwScheduleActionTypes.UNPUBLISH}`\n )\n }),\n entryId: string({\n validation: validation.create(`required`)\n }),\n modelId: string({\n validation: (value: string) => {\n if (instance.type !== ApwContentTypes.CMS_ENTRY) {\n return true;\n } else if (!!value) {\n return true;\n }\n throw new Error(\n `There is no modelId defined when type is \"${ApwContentTypes.CMS_ENTRY}\"`\n );\n }\n })\n };\n})();\n\ninterface GetTenantAndLocaleResult {\n tenant: string;\n locale: string;\n}\n\nexport function createScheduleActionMethods({\n storageOperations,\n getIdentity,\n getTenant,\n getLocale\n}: CreateScheduleActionParams): ApwScheduleActionCrud {\n const getTenantAndLocale = (): GetTenantAndLocaleResult => {\n const tenant = getTenant().id;\n const locale = getLocale().code;\n return {\n tenant,\n locale\n };\n };\n return {\n async get(id) {\n return storageOperations.get({\n where: {\n id,\n ...getTenantAndLocale()\n }\n });\n },\n async list(params) {\n return storageOperations.list({\n ...params,\n where: {\n ...params.where,\n ...getTenantAndLocale()\n }\n });\n },\n async create(input) {\n const createDataModel = new CreateDataModel().populate(input);\n\n await createDataModel.validate();\n\n const id: string = mdbid();\n const identity = getIdentity();\n\n const data: ApwScheduleActionData = await createDataModel.toJSON();\n\n const scheduleAction: ApwScheduleAction = {\n ...getTenantAndLocale(),\n data,\n id,\n createdOn: new Date().toISOString(),\n savedOn: new Date().toISOString(),\n createdBy: {\n id: identity.id,\n type: identity.type,\n displayName: identity.displayName\n }\n };\n\n return await storageOperations.create({\n item: scheduleAction,\n input\n });\n },\n async update(id, data) {\n const updateDataModel = new CreateDataModel().populate(data);\n\n await updateDataModel.validate();\n\n const original = await this.get(id);\n\n if (!original) {\n throw new Error(\"Not found!\");\n }\n\n return await storageOperations.update({ item: original, input: data });\n },\n async delete(id: string) {\n await storageOperations.delete({ id, ...getTenantAndLocale() });\n\n return true;\n },\n async getCurrentTask() {\n return await storageOperations.getCurrentTask({ where: { ...getTenantAndLocale() } });\n },\n async updateCurrentTask(item) {\n return await storageOperations.updateCurrentTask({ item });\n },\n async deleteCurrentTask() {\n return await storageOperations.deleteCurrentTask({ ...getTenantAndLocale() });\n }\n };\n}\n"],"mappings":";;;;;;;;AAIA;AACA;AACA;AACA;AAPA;AACA;AACA;AACA;;AAaA,
|
1
|
+
{"version":3,"names":["_fields","require","_validation","_utils","_types","CreateDataModel","withFields","instance","datetime","string","validation","create","type","ApwContentTypes","PAGE","CMS_ENTRY","action","ApwScheduleActionTypes","PUBLISH","UNPUBLISH","entryId","modelId","value","Error","createScheduleActionMethods","storageOperations","getIdentity","getTenant","getLocale","getTenantAndLocale","tenant","id","locale","code","get","where","_objectSpread2","default","list","params","input","createDataModel","populate","validate","mdbid","identity","data","toJSON","scheduleAction","createdOn","Date","toISOString","savedOn","createdBy","displayName","item","update","updateDataModel","original","delete","getCurrentTask","updateCurrentTask","deleteCurrentTask"],"sources":["createScheduleActionMethods.ts"],"sourcesContent":["/**\n * Package @commodo/fields does not have types.\n */\n// @ts-ignore\nimport { string, withFields } from \"@commodo/fields\";\nimport { validation } from \"@webiny/validation\";\nimport { mdbid } from \"@webiny/utils\";\nimport {\n ApwContentTypes,\n ApwScheduleAction,\n ApwScheduleActionCrud,\n ApwScheduleActionData,\n ApwScheduleActionTypes,\n CreateScheduleActionParams\n} from \"~/scheduler/types\";\n\nconst CreateDataModel = withFields((instance: any) => {\n return {\n datetime: string({\n validation: validation.create(`required`)\n }),\n type: string({\n validation: validation.create(\n `required,in:${ApwContentTypes.PAGE}:${ApwContentTypes.CMS_ENTRY}`\n )\n }),\n action: string({\n validation: validation.create(\n `required,in:${ApwScheduleActionTypes.PUBLISH}:${ApwScheduleActionTypes.UNPUBLISH}`\n )\n }),\n entryId: string({\n validation: validation.create(`required`)\n }),\n modelId: string({\n validation: (value: string) => {\n if (instance.type !== ApwContentTypes.CMS_ENTRY) {\n return true;\n } else if (!!value) {\n return true;\n }\n throw new Error(\n `There is no modelId defined when type is \"${ApwContentTypes.CMS_ENTRY}\"`\n );\n }\n })\n };\n})();\n\ninterface GetTenantAndLocaleResult {\n tenant: string;\n locale: string;\n}\n\nexport function createScheduleActionMethods({\n storageOperations,\n getIdentity,\n getTenant,\n getLocale\n}: CreateScheduleActionParams): ApwScheduleActionCrud {\n const getTenantAndLocale = (): GetTenantAndLocaleResult => {\n const tenant = getTenant().id;\n const locale = getLocale().code;\n return {\n tenant,\n locale\n };\n };\n return {\n async get(id) {\n return storageOperations.get({\n where: {\n id,\n ...getTenantAndLocale()\n }\n });\n },\n async list(params) {\n return storageOperations.list({\n ...params,\n where: {\n ...params.where,\n ...getTenantAndLocale()\n }\n });\n },\n async create(input) {\n const createDataModel = new CreateDataModel().populate(input);\n\n await createDataModel.validate();\n\n const id: string = mdbid();\n const identity = getIdentity();\n\n const data: ApwScheduleActionData = await createDataModel.toJSON();\n\n const scheduleAction: ApwScheduleAction = {\n ...getTenantAndLocale(),\n data,\n id,\n createdOn: new Date().toISOString(),\n savedOn: new Date().toISOString(),\n createdBy: {\n id: identity.id,\n type: identity.type,\n displayName: identity.displayName\n }\n };\n\n return await storageOperations.create({\n item: scheduleAction,\n input\n });\n },\n async update(id, data) {\n const updateDataModel = new CreateDataModel().populate(data);\n\n await updateDataModel.validate();\n\n const original = await this.get(id);\n\n if (!original) {\n throw new Error(\"Not found!\");\n }\n\n return await storageOperations.update({ item: original, input: data });\n },\n async delete(id: string) {\n await storageOperations.delete({ id, ...getTenantAndLocale() });\n\n return true;\n },\n async getCurrentTask() {\n return await storageOperations.getCurrentTask({ where: { ...getTenantAndLocale() } });\n },\n async updateCurrentTask(item) {\n return await storageOperations.updateCurrentTask({ item });\n },\n async deleteCurrentTask() {\n return await storageOperations.deleteCurrentTask({ ...getTenantAndLocale() });\n }\n };\n}\n"],"mappings":";;;;;;;;AAIA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,WAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAF,OAAA;AACA,IAAAG,MAAA,GAAAH,OAAA;AAPA;AACA;AACA;AACA;;AAaA,MAAMI,eAAe,GAAG,IAAAC,kBAAU,EAAEC,QAAa,IAAK;EAClD,OAAO;IACHC,QAAQ,EAAE,IAAAC,cAAM,EAAC;MACbC,UAAU,EAAEA,sBAAU,CAACC,MAAM,CAAE,UAAS;IAC5C,CAAC,CAAC;IACFC,IAAI,EAAE,IAAAH,cAAM,EAAC;MACTC,UAAU,EAAEA,sBAAU,CAACC,MAAM,CACxB,eAAcE,sBAAe,CAACC,IAAK,IAAGD,sBAAe,CAACE,SAAU,EACrE;IACJ,CAAC,CAAC;IACFC,MAAM,EAAE,IAAAP,cAAM,EAAC;MACXC,UAAU,EAAEA,sBAAU,CAACC,MAAM,CACxB,eAAcM,6BAAsB,CAACC,OAAQ,IAAGD,6BAAsB,CAACE,SAAU,EACtF;IACJ,CAAC,CAAC;IACFC,OAAO,EAAE,IAAAX,cAAM,EAAC;MACZC,UAAU,EAAEA,sBAAU,CAACC,MAAM,CAAE,UAAS;IAC5C,CAAC,CAAC;IACFU,OAAO,EAAE,IAAAZ,cAAM,EAAC;MACZC,UAAU,EAAGY,KAAa,IAAK;QA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,KAAAvB,cAAA,CAAAC,OAAA;QAAGN;MAAE,GAAKF,kBAAkB,CAAC,CAAC,CAAE,CAAC;MAE/D,OAAO,IAAI;IACf,CAAC;IACD,MAAM+B,cAAcA,CAAA,EAAG;MACnB,OAAO,MAAMnC,iBAAiB,CAACmC,cAAc,CAAC;QAAEzB,KAAK,MAAAC,cAAA,CAAAC,OAAA,MAAOR,kBAAkB,CAAC,CAAC;MAAG,CAAC,CAAC;IACzF,CAAC;IACD,MAAMgC,iBAAiBA,CAACN,IAAI,EAAE;MAC1B,OAAO,MAAM9B,iBAAiB,CAACoC,iBAAiB,CAAC;QAAEN;MAAK,CAAC,CAAC;IAC9D,CAAC;IACD,MAAMO,iBAAiBA,CAAA,EAAG;MACtB,OAAO,MAAMrC,iBAAiB,CAACqC,iBAAiB,KAAA1B,cAAA,CAAAC,OAAA,MAAMR,kBAAkB,CAAC,CAAC,CAAE,CAAC;IACjF;EACJ,CAAC;AACL"}
|
@@ -144,8 +144,8 @@ const createExecuteActionLambda = params => {
|
|
144
144
|
* Check for the response and log the error if any.
|
145
145
|
*/
|
146
146
|
if (response !== null && response !== void 0 && response.body) {
|
147
|
-
var _response$body$data
|
148
|
-
const error = (_response$body$data = response.body.data) === null || _response$body$data === void 0
|
147
|
+
var _response$body$data;
|
148
|
+
const error = (_response$body$data = response.body.data) === null || _response$body$data === void 0 || (_response$body$data = _response$body$data.content) === null || _response$body$data === void 0 ? void 0 : _response$body$data.error;
|
149
149
|
if (!error) {
|
150
150
|
console.log("Invoke successful.");
|
151
151
|
continue;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["createExecuteActionLambda","params","storageOperations","createRawEventHandler","payload","context","log","console","applicationGraphQLPlugins","plugins","byType","ApplicationGraphQL","type","length","error","applicationGraphQLPluginCache","getApplicationGraphQLPlugin","data","plugin","canUse","apwSettings","getApwSettings","futureDatetime","datetime","locale","tenant","items","list","where","datetime_startsWith","getIsoStringTillMinutes","sort","limit","item","action","JSON","stringify","name","getArn","settings","url","getUrl","body","getGraphQLBody","response","handlerClient","invoke","httpMethod","path","headers","Authorization","encodeToken","id","await","delete","content","ex","message","code","executeActionHandlerPlugins","config","ContextPlugin","register","PageBuilderGraphQL","HeadlessCMSGraphQL","basePlugins"],"sources":["index.ts"],"sourcesContent":["import { ApwScheduleActionData, ApwScheduleActionStorageOperations } from \"~/scheduler/types\";\nimport { getIsoStringTillMinutes, encodeToken, basePlugins } from \"~/scheduler/handlers/utils\";\nimport { getApwSettings } from \"~/scheduler/handlers/utils\";\nimport { ContextPlugin } from \"@webiny/api\";\nimport { PageBuilderGraphQL } from \"./plugins/PageBuilderGraphQL\";\nimport { HeadlessCMSGraphQL } from \"./plugins/HeadlessCMSGraphQL\";\nimport { ApplicationGraphQL } from \"./plugins/ApplicationGraphQL\";\nimport { createRawEventHandler } from \"@webiny/handler-aws\";\n\nexport interface HandlerArgs {\n datetime: string;\n tenant: string;\n locale: string;\n futureDatetime?: string;\n}\n\ninterface Configuration {\n storageOperations: ApwScheduleActionStorageOperations;\n}\n\n/**\n * Handler that execute the provided action(s) for the schedule action workflow.\n */\nconst createExecuteActionLambda = (params: Configuration) => {\n const { storageOperations } = params;\n\n return createRawEventHandler<HandlerArgs>(async ({ payload, context }) => {\n const log = console.log;\n\n const applicationGraphQLPlugins = context.plugins.byType<ApplicationGraphQL>(\n ApplicationGraphQL.type\n );\n\n if (applicationGraphQLPlugins.length === 0) {\n console.error(`There are no plugins to determine GraphQL endpoints or mutations.`);\n return;\n }\n\n const applicationGraphQLPluginCache: Record<string, ApplicationGraphQL> = {};\n\n const getApplicationGraphQLPlugin = (\n data: ApwScheduleActionData\n ): ApplicationGraphQL | null => {\n const { type } = data;\n if (applicationGraphQLPluginCache[type]) {\n return applicationGraphQLPluginCache[type];\n }\n for (const plugin of applicationGraphQLPlugins) {\n if (!plugin.canUse(data)) {\n continue;\n }\n applicationGraphQLPluginCache[type] = plugin;\n return plugin;\n }\n return null;\n };\n\n try {\n const apwSettings = await getApwSettings();\n\n const { futureDatetime: datetime, locale, tenant } = payload;\n /**\n * If there is no datetime we bail out early.\n */\n if (!datetime || typeof datetime !== \"string\") {\n log(`Bailing out!!`);\n return;\n }\n\n /**\n * Get tasks from the DB by datetime.\n */\n const [items] = await storageOperations.list({\n where: {\n tenant,\n locale,\n datetime_startsWith: getIsoStringTillMinutes(datetime)\n },\n sort: [\"datetime_ASC\"],\n limit: 1000\n });\n\n /**\n * Execute all actions.\n */\n if (!items || items.length === 0) {\n return;\n }\n log(`Found ${items.length} actions.`);\n for (const item of items) {\n log(\n `Performing mutation \"${item.data.action}\" on \"${item.data.type}\" at \"${item.data.datetime}\"`\n );\n\n const plugin = getApplicationGraphQLPlugin(item.data);\n if (!plugin) {\n console.error(\n `There is no plugin to determine GraphQL endpoint and mutations for type \"${item.data.type}\".`\n );\n console.log(JSON.stringify(item));\n continue;\n }\n\n const name = plugin.getArn(apwSettings);\n if (!name) {\n console.error(`There is no FunctionName found for type \"${item.data.type}\".`);\n console.log(\n JSON.stringify({\n item,\n settings: apwSettings\n })\n );\n continue;\n }\n\n const url = plugin.getUrl({\n locale,\n tenant\n });\n if (!url) {\n console.error(\n `There is no url defined, in the Plugin, for type \"${item.data.type}\".`\n );\n console.log(JSON.stringify(item));\n continue;\n }\n\n const body = plugin.getGraphQLBody(item.data);\n\n if (!body) {\n console.error(\n `There is no GraphQL body defined, in the Plugin, for type \"${item.data.type}\".`\n );\n console.log(JSON.stringify(item));\n continue;\n }\n\n console.log(`Invoking Lambda \"${name}\" with url \"${url}\".`);\n // Perform the actual action call.\n const response = await context.handlerClient.invoke({\n name,\n payload: {\n httpMethod: \"POST\",\n path: url,\n headers: {\n [\"content-type\"]: \"application/json\",\n Authorization: encodeToken({\n id: item.id,\n locale: item.locale,\n tenant: item.tenant\n }),\n [\"x-tenant\"]: tenant,\n [\"x-i18n-locale\"]: `default:${locale};content:${locale};`\n },\n body: JSON.stringify(body)\n },\n await: true\n });\n /**\n *\n */\n await storageOperations.delete({\n locale,\n tenant,\n id: item.id\n });\n /**\n * Check for the response and log the error if any.\n */\n if (response?.body) {\n const error = response.body.data?.content?.error;\n if (!error) {\n console.log(\"Invoke successful.\");\n continue;\n }\n console.log(JSON.stringify({ error }, null, 2));\n continue;\n }\n console.log(JSON.stringify({ response }, null, 2));\n\n // TODO: Maybe update the status like error in original item in DB.\n }\n } catch (ex) {\n console.error(\n \"[HANDLER_EXECUTE_ACTION] => \",\n JSON.stringify({\n message: ex.message,\n code: ex.code,\n data: ex.data\n })\n );\n // TODO: Maybe update the status like error in original item in DB.\n }\n });\n};\n\nexport const executeActionHandlerPlugins = (config: Configuration) => [\n new ContextPlugin(async context => {\n context.plugins.register([new PageBuilderGraphQL(), new HeadlessCMSGraphQL()]);\n }),\n basePlugins(),\n createExecuteActionLambda(config)\n];\n"],"mappings":";;;;;;AACA;AAEA;AACA;AACA;AACA;AACA;AAaA;AACA;AACA;AACA,MAAMA,yBAAyB,GAAIC,MAAqB,IAAK;EACzD,MAAM;IAAEC;EAAkB,CAAC,GAAGD,MAAM;EAEpC,OAAO,IAAAE,iCAAqB,EAAc,OAAO;IAAEC,OAAO;IAAEC;EAAQ,CAAC,KAAK;IACtE,MAAMC,GAAG,GAAGC,OAAO,CAACD,GAAG;IAEvB,MAAME,yBAAyB,GAAGH,OAAO,CAACI,OAAO,CAACC,MAAM,CACpDC,sCAAkB,CAACC,IAAI,CAC1B;IAED,IAAIJ,yBAAyB,CAACK,MAAM,KAAK,CAAC,EAAE;MACxCN,OAAO,CAACO,KAAK,CAAE,mEAAkE,CAAC;MAClF;IACJ;IAEA,MAAMC,6BAAiE,GAAG,CAAC,CAAC;IAE5E,MAAMC,2BAA2B,GAC7BC,IAA2B,IACC;MAC5B,MAAM;QAAEL;MAAK,CAAC,GAAGK,IAAI;MACrB,IAAIF,6BAA6B,CAACH,IAAI,CAAC,EAAE;QACrC,OAAOG,6BAA6B,CAACH,IAAI,CAAC;MAC9C;MACA,KAAK,MAAMM,MAAM,IAAI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CAACC,OAAO;QACnBC,IAAI,EAAEF,EAAE,CAACE,IAAI;QACbzC,IAAI,EAAEuC,EAAE,CAACvC;MACb,CAAC,CAAC,CACL;MACD;IACJ;EACJ,CAAC,CAAC;AACN,CAAC;;AAEM,MAAM0C,2BAA2B,GAAIC,MAAqB,IAAK,CAClE,IAAIC,kBAAa,CAAC,MAAMxD,OAAO,IAAI;EAC/BA,OAAO,CAACI,OAAO,CAACqD,QAAQ,CAAC,CAAC,IAAIC,sCAAkB,EAAE,EAAE,IAAIC,sCAAkB,EAAE,CAAC,CAAC;AAClF,CAAC,CAAC,EACF,IAAAC,kBAAW,GAAE,EACbjE,yBAAyB,CAAC4D,MAAM,CAAC,CACpC;AAAC"}
|
1
|
+
{"version":3,"names":["_utils","require","_api","_PageBuilderGraphQL","_HeadlessCMSGraphQL","_ApplicationGraphQL","_handlerAws","createExecuteActionLambda","params","storageOperations","createRawEventHandler","payload","context","log","console","applicationGraphQLPlugins","plugins","byType","ApplicationGraphQL","type","length","error","applicationGraphQLPluginCache","getApplicationGraphQLPlugin","data","plugin","canUse","apwSettings","getApwSettings","futureDatetime","datetime","locale","tenant","items","list","where","datetime_startsWith","getIsoStringTillMinutes","sort","limit","item","action","JSON","stringify","name","getArn","settings","url","getUrl","body","getGraphQLBody","response","handlerClient","invoke","httpMethod","path","headers","Authorization","encodeToken","id","await","delete","_response$body$data","content","ex","message","code","executeActionHandlerPlugins","config","ContextPlugin","register","PageBuilderGraphQL","HeadlessCMSGraphQL","basePlugins","exports"],"sources":["index.ts"],"sourcesContent":["import { ApwScheduleActionData, ApwScheduleActionStorageOperations } from \"~/scheduler/types\";\nimport { getIsoStringTillMinutes, encodeToken, basePlugins } from \"~/scheduler/handlers/utils\";\nimport { getApwSettings } from \"~/scheduler/handlers/utils\";\nimport { ContextPlugin } from \"@webiny/api\";\nimport { PageBuilderGraphQL } from \"./plugins/PageBuilderGraphQL\";\nimport { HeadlessCMSGraphQL } from \"./plugins/HeadlessCMSGraphQL\";\nimport { ApplicationGraphQL } from \"./plugins/ApplicationGraphQL\";\nimport { createRawEventHandler } from \"@webiny/handler-aws\";\n\nexport interface HandlerArgs {\n datetime: string;\n tenant: string;\n locale: string;\n futureDatetime?: string;\n}\n\ninterface Configuration {\n storageOperations: ApwScheduleActionStorageOperations;\n}\n\n/**\n * Handler that execute the provided action(s) for the schedule action workflow.\n */\nconst createExecuteActionLambda = (params: Configuration) => {\n const { storageOperations } = params;\n\n return createRawEventHandler<HandlerArgs>(async ({ payload, context }) => {\n const log = console.log;\n\n const applicationGraphQLPlugins = context.plugins.byType<ApplicationGraphQL>(\n ApplicationGraphQL.type\n );\n\n if (applicationGraphQLPlugins.length === 0) {\n console.error(`There are no plugins to determine GraphQL endpoints or mutations.`);\n return;\n }\n\n const applicationGraphQLPluginCache: Record<string, ApplicationGraphQL> = {};\n\n const getApplicationGraphQLPlugin = (\n data: ApwScheduleActionData\n ): ApplicationGraphQL | null => {\n const { type } = data;\n if (applicationGraphQLPluginCache[type]) {\n return applicationGraphQLPluginCache[type];\n }\n for (const plugin of applicationGraphQLPlugins) {\n if (!plugin.canUse(data)) {\n continue;\n }\n applicationGraphQLPluginCache[type] = plugin;\n return plugin;\n }\n return null;\n };\n\n try {\n const apwSettings = await getApwSettings();\n\n const { futureDatetime: datetime, locale, tenant } = payload;\n /**\n * If there is no datetime we bail out early.\n */\n if (!datetime || typeof datetime !== \"string\") {\n log(`Bailing out!!`);\n return;\n }\n\n /**\n * Get tasks from the DB by datetime.\n */\n const [items] = await storageOperations.list({\n where: {\n tenant,\n locale,\n datetime_startsWith: getIsoStringTillMinutes(datetime)\n },\n sort: [\"datetime_ASC\"],\n limit: 1000\n });\n\n /**\n * Execute all actions.\n */\n if (!items || items.length === 0) {\n return;\n }\n log(`Found ${items.length} actions.`);\n for (const item of items) {\n log(\n `Performing mutation \"${item.data.action}\" on \"${item.data.type}\" at \"${item.data.datetime}\"`\n );\n\n const plugin = getApplicationGraphQLPlugin(item.data);\n if (!plugin) {\n console.error(\n `There is no plugin to determine GraphQL endpoint and mutations for type \"${item.data.type}\".`\n );\n console.log(JSON.stringify(item));\n continue;\n }\n\n const name = plugin.getArn(apwSettings);\n if (!name) {\n console.error(`There is no FunctionName found for type \"${item.data.type}\".`);\n console.log(\n JSON.stringify({\n item,\n settings: apwSettings\n })\n );\n continue;\n }\n\n const url = plugin.getUrl({\n locale,\n tenant\n });\n if (!url) {\n console.error(\n `There is no url defined, in the Plugin, for type \"${item.data.type}\".`\n );\n console.log(JSON.stringify(item));\n continue;\n }\n\n const body = plugin.getGraphQLBody(item.data);\n\n if (!body) {\n console.error(\n `There is no GraphQL body defined, in the Plugin, for type \"${item.data.type}\".`\n );\n console.log(JSON.stringify(item));\n continue;\n }\n\n console.log(`Invoking Lambda \"${name}\" with url \"${url}\".`);\n // Perform the actual action call.\n const response = await context.handlerClient.invoke({\n name,\n payload: {\n httpMethod: \"POST\",\n path: url,\n headers: {\n [\"content-type\"]: \"application/json\",\n Authorization: encodeToken({\n id: item.id,\n locale: item.locale,\n tenant: item.tenant\n }),\n [\"x-tenant\"]: tenant,\n [\"x-i18n-locale\"]: `default:${locale};content:${locale};`\n },\n body: JSON.stringify(body)\n },\n await: true\n });\n /**\n *\n */\n await storageOperations.delete({\n locale,\n tenant,\n id: item.id\n });\n /**\n * Check for the response and log the error if any.\n */\n if (response?.body) {\n const error = response.body.data?.content?.error;\n if (!error) {\n console.log(\"Invoke successful.\");\n continue;\n }\n console.log(JSON.stringify({ error }, null, 2));\n continue;\n }\n console.log(JSON.stringify({ response }, null, 2));\n\n // TODO: Maybe update the status like error in original item in DB.\n }\n } catch (ex) {\n console.error(\n \"[HANDLER_EXECUTE_ACTION] => \",\n JSON.stringify({\n message: ex.message,\n code: ex.code,\n data: ex.data\n })\n );\n // TODO: Maybe update the status like error in original item in DB.\n }\n });\n};\n\nexport const executeActionHandlerPlugins = (config: Configuration) => [\n new ContextPlugin(async context => {\n context.plugins.register([new PageBuilderGraphQL(), new HeadlessCM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AIC,kBAAa,CAAC,MAAMzD,OAAO,IAAI;EAC/BA,OAAO,CAACI,OAAO,CAACsD,QAAQ,CAAC,CAAC,IAAIC,sCAAkB,CAAC,CAAC,EAAE,IAAIC,sCAAkB,CAAC,CAAC,CAAC,CAAC;AAClF,CAAC,CAAC,EACF,IAAAC,kBAAW,EAAC,CAAC,EACblE,yBAAyB,CAAC6D,MAAM,CAAC,CACpC;AAACM,OAAA,CAAAP,2BAAA,GAAAA,2BAAA"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["ApplicationGraphQL","Plugin"],"sources":["ApplicationGraphQL.ts"],"sourcesContent":["import { Plugin } from \"@webiny/plugins/Plugin\";\nimport { ApwScheduleActionData } from \"~/scheduler/types\";\nimport { ApwSettings } from \"~/scheduler/handlers/utils\";\n\nexport { ApwScheduleActionData, ApwSettings };\n\nexport interface ApplicationGraphQLGetUrlParams {\n tenant: string;\n locale: string;\n}\nexport interface ApplicationGraphQLBody<T = Record<string, any>> {\n query: string;\n variables: T;\n}\n\nexport abstract class ApplicationGraphQL extends Plugin {\n public static override readonly type: string = \"apw.scheduler.applicationGraphQL\";\n\n public abstract getUrl(params: ApplicationGraphQLGetUrlParams): string;\n\n public abstract canUse(data: ApwScheduleActionData): boolean;\n\n public abstract getArn(settings: ApwSettings): string;\n\n public abstract getGraphQLBody(data: ApwScheduleActionData): ApplicationGraphQLBody | null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AAaO,
|
1
|
+
{"version":3,"names":["_Plugin","require","_types","_utils","ApplicationGraphQL","Plugin","exports","_defineProperty2","default"],"sources":["ApplicationGraphQL.ts"],"sourcesContent":["import { Plugin } from \"@webiny/plugins/Plugin\";\nimport { ApwScheduleActionData } from \"~/scheduler/types\";\nimport { ApwSettings } from \"~/scheduler/handlers/utils\";\n\nexport { ApwScheduleActionData, ApwSettings };\n\nexport interface ApplicationGraphQLGetUrlParams {\n tenant: string;\n locale: string;\n}\nexport interface ApplicationGraphQLBody<T = Record<string, any>> {\n query: string;\n variables: T;\n}\n\nexport abstract class ApplicationGraphQL extends Plugin {\n public static override readonly type: string = \"apw.scheduler.applicationGraphQL\";\n\n public abstract getUrl(params: ApplicationGraphQLGetUrlParams): string;\n\n public abstract canUse(data: ApwScheduleActionData): boolean;\n\n public abstract getArn(settings: ApwSettings): string;\n\n public abstract getGraphQLBody(data: ApwScheduleActionData): ApplicationGraphQLBody | null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAF,OAAA;AAaO,MAAeG,kBAAkB,SAASC,cAAM,CAAC;AAUvDC,OAAA,CAAAF,kBAAA,GAAAA,kBAAA;AAAA,IAAAG,gBAAA,CAAAC,OAAA,EAVqBJ,kBAAkB,UACW,kCAAkC"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["META_FIELDS","ERROR_FIELD","createPublishMutation","modelId","ucFirstModelId","upperFirst","createUnpublishMutation","HeadlessCMSGraphQL","ApplicationGraphQL","canUse","data","type","ApwContentTypes","CMS_ENTRY","getUrl","locale","getArn","settings","mainGraphqlFunctionArn","getGraphQLBody","action","ApwScheduleActionTypes","PUBLISH","getPublishBody","UNPUBLISH","getUnpublishBody","WebinyError","query","variables","revision","entryId"],"sources":["HeadlessCMSGraphQL.ts"],"sourcesContent":["import {\n ApplicationGraphQL,\n ApplicationGraphQLBody,\n ApwSettings,\n ApplicationGraphQLGetUrlParams,\n ApwScheduleActionData\n} from \"./ApplicationGraphQL\";\nimport { ApwContentTypes, ApwScheduleActionTypes } from \"~/scheduler/types\";\nimport WebinyError from \"@webiny/error\";\nimport upperFirst from \"lodash/upperFirst\";\n\nconst META_FIELDS = `\n title\n publishedOn\n version\n locked\n status\n`;\n\nconst ERROR_FIELD = `\n {\n code\n data\n message\n }\n`;\n\nconst createPublishMutation = (modelId: string): string => {\n const ucFirstModelId = upperFirst(modelId);\n\n return `\n mutation CmsPublish${ucFirstModelId}($revision: ID!) {\n content: publish${ucFirstModelId}(revision: $revision) {\n data {\n id\n meta {\n ${META_FIELDS}\n }\n }\n error ${ERROR_FIELD}\n }\n }`;\n};\n\nconst createUnpublishMutation = (modelId: string) => {\n const ucFirstModelId = upperFirst(modelId);\n\n return `\n mutation CmsUnpublish${ucFirstModelId}($revision: ID!) {\n content: unpublish${ucFirstModelId}(revision: $revision) {\n data {\n id\n meta {\n ${META_FIELDS}\n }\n }\n error ${ERROR_FIELD}\n }\n }`;\n};\n\ninterface ApplicationGraphQLBodyVariables {\n revision: string;\n}\n\nexport class HeadlessCMSGraphQL extends ApplicationGraphQL {\n public override name = \"apw.scheduler.applicationGraphQL.headlessCms\";\n\n public override canUse(data: ApwScheduleActionData): boolean {\n return data.type === ApwContentTypes.CMS_ENTRY;\n }\n\n public override getUrl({ locale }: ApplicationGraphQLGetUrlParams): string {\n return `/cms/manage/${locale}`;\n }\n\n public override getArn(settings: ApwSettings): string {\n return settings.mainGraphqlFunctionArn;\n }\n\n public override getGraphQLBody(data: ApwScheduleActionData): ApplicationGraphQLBody | null {\n switch (data.action) {\n case ApwScheduleActionTypes.PUBLISH:\n return this.getPublishBody(data);\n case ApwScheduleActionTypes.UNPUBLISH:\n return this.getUnpublishBody(data);\n default:\n return null;\n }\n }\n\n private getPublishBody(\n data: ApwScheduleActionData\n ): ApplicationGraphQLBody<ApplicationGraphQLBodyVariables> {\n if (!data.modelId) {\n throw new WebinyError(\n \"Missing model ID in the schedule action data.\",\n \"SCHEDULE_ACTION_ERROR\",\n {\n data\n }\n );\n }\n return {\n query: createPublishMutation(data.modelId),\n variables: {\n revision: data.entryId\n }\n };\n }\n\n private getUnpublishBody(\n data: ApwScheduleActionData\n ): ApplicationGraphQLBody<ApplicationGraphQLBodyVariables> {\n if (!data.modelId) {\n throw new WebinyError(\n \"Missing model ID in the schedule action data.\",\n \"SCHEDULE_ACTION_ERROR\",\n {\n data\n }\n );\n }\n return {\n query: createUnpublishMutation(data.modelId),\n variables: {\n revision: data.entryId\n }\n };\n }\n}\n"],"mappings":";;;;;;;;AAAA;AAOA;AACA;AACA;AAEA,
|
1
|
+
{"version":3,"names":["_ApplicationGraphQL","require","_types","_error","_interopRequireDefault","_upperFirst","META_FIELDS","ERROR_FIELD","createPublishMutation","modelId","ucFirstModelId","upperFirst","createUnpublishMutation","HeadlessCMSGraphQL","ApplicationGraphQL","constructor","args","_defineProperty2","default","canUse","data","type","ApwContentTypes","CMS_ENTRY","getUrl","locale","getArn","settings","mainGraphqlFunctionArn","getGraphQLBody","action","ApwScheduleActionTypes","PUBLISH","getPublishBody","UNPUBLISH","getUnpublishBody","WebinyError","query","variables","revision","entryId","exports"],"sources":["HeadlessCMSGraphQL.ts"],"sourcesContent":["import {\n ApplicationGraphQL,\n ApplicationGraphQLBody,\n ApwSettings,\n ApplicationGraphQLGetUrlParams,\n ApwScheduleActionData\n} from \"./ApplicationGraphQL\";\nimport { ApwContentTypes, ApwScheduleActionTypes } from \"~/scheduler/types\";\nimport WebinyError from \"@webiny/error\";\nimport upperFirst from \"lodash/upperFirst\";\n\nconst META_FIELDS = `\n title\n publishedOn\n version\n locked\n status\n`;\n\nconst ERROR_FIELD = `\n {\n code\n data\n message\n }\n`;\n\nconst createPublishMutation = (modelId: string): string => {\n const ucFirstModelId = upperFirst(modelId);\n\n return `\n mutation CmsPublish${ucFirstModelId}($revision: ID!) {\n content: publish${ucFirstModelId}(revision: $revision) {\n data {\n id\n meta {\n ${META_FIELDS}\n }\n }\n error ${ERROR_FIELD}\n }\n }`;\n};\n\nconst createUnpublishMutation = (modelId: string) => {\n const ucFirstModelId = upperFirst(modelId);\n\n return `\n mutation CmsUnpublish${ucFirstModelId}($revision: ID!) {\n content: unpublish${ucFirstModelId}(revision: $revision) {\n data {\n id\n meta {\n ${META_FIELDS}\n }\n }\n error ${ERROR_FIELD}\n }\n }`;\n};\n\ninterface ApplicationGraphQLBodyVariables {\n revision: string;\n}\n\nexport class HeadlessCMSGraphQL extends ApplicationGraphQL {\n public override name = \"apw.scheduler.applicationGraphQL.headlessCms\";\n\n public override canUse(data: ApwScheduleActionData): boolean {\n return data.type === ApwContentTypes.CMS_ENTRY;\n }\n\n public override getUrl({ locale }: ApplicationGraphQLGetUrlParams): string {\n return `/cms/manage/${locale}`;\n }\n\n public override getArn(settings: ApwSettings): string {\n return settings.mainGraphqlFunctionArn;\n }\n\n public override getGraphQLBody(data: ApwScheduleActionData): ApplicationGraphQLBody | null {\n switch (data.action) {\n case ApwScheduleActionTypes.PUBLISH:\n return this.getPublishBody(data);\n case ApwScheduleActionTypes.UNPUBLISH:\n return this.getUnpublishBody(data);\n default:\n return null;\n }\n }\n\n private getPublishBody(\n data: ApwScheduleActionData\n ): ApplicationGraphQLBody<ApplicationGraphQLBodyVariables> {\n if (!data.modelId) {\n throw new WebinyError(\n \"Missing model ID in the schedule action data.\",\n \"SCHEDULE_ACTION_ERROR\",\n {\n data\n }\n );\n }\n return {\n query: createPublishMutation(data.modelId),\n variables: {\n revision: data.entryId\n }\n };\n }\n\n private getUnpublishBody(\n data: ApwScheduleActionData\n ): ApplicationGraphQLBody<ApplicationGraphQLBodyVariables> {\n if (!data.modelId) {\n throw new WebinyError(\n \"Missing model ID in the schedule action data.\",\n \"SCHEDULE_ACTION_ERROR\",\n {\n data\n }\n );\n }\n return {\n query: createUnpublishMutation(data.modelId),\n variables: {\n revision: data.entryId\n }\n };\n }\n}\n"],"mappings":";;;;;;;;AAAA,IAAAA,mBAAA,GAAAC,OAAA;AAOA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAC,sBAAA,CAAAH,OAAA;AACA,IAAAI,WAAA,GAAAD,sBAAA,CAAAH,OAAA;AAEA,MAAMK,WAAW,GAAI;AACrB;AACA;AACA;AACA;AACA;AACA,CAAC;AAED,MAAMC,WAAW,GAAI;AACrB;AACA;AACA;AACA;AACA;AACA,CAAC;AAED,MAAMC,qBAAq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O,EAAE;MACf,MAAM,IAAI2B,cAAW,CACjB,+CAA+C,EAC/C,uBAAuB,EACvB;QACIhB;MACJ,CACJ,CAAC;IACL;IACA,OAAO;MACHiB,KAAK,EAAE7B,qBAAqB,CAACY,IAAI,CAACX,OAAO,CAAC;MAC1C6B,SAAS,EAAE;QACPC,QAAQ,EAAEnB,IAAI,CAACoB;MACnB;IACJ,CAAC;EACL;EAEQL,gBAAgBA,CACpBf,IAA2B,EAC4B;IACvD,IAAI,CAACA,IAAI,CAACX,OAAO,EAAE;MACf,MAAM,IAAI2B,cAAW,CACjB,+CAA+C,EAC/C,uBAAuB,EACvB;QACIhB;MACJ,CACJ,CAAC;IACL;IACA,OAAO;MACHiB,KAAK,EAAEzB,uBAAuB,CAACQ,IAAI,CAACX,OAAO,CAAC;MAC5C6B,SAAS,EAAE;QACPC,QAAQ,EAAEnB,IAAI,CAACoB;MACnB;IACJ,CAAC;EACL;AACJ;AAACC,OAAA,CAAA5B,kBAAA,GAAAA,kBAAA"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["PB_PAGE_DATA_FIELD","ERROR_FIELD","PUBLISH_MUTATION","UNPUBLISH_MUTATION","PageBuilderGraphQL","ApplicationGraphQL","canUse","data","type","ApwContentTypes","PAGE","getUrl","getArn","settings","mainGraphqlFunctionArn","getGraphQLBody","action","ApwScheduleActionTypes","PUBLISH","getPublishBody","UNPUBLISH","getUnpublishBody","query","variables","id","entryId"],"sources":["PageBuilderGraphQL.ts"],"sourcesContent":["import {\n ApplicationGraphQL,\n ApplicationGraphQLBody,\n ApwScheduleActionData\n} from \"./ApplicationGraphQL\";\nimport { ApwContentTypes, ApwScheduleActionTypes } from \"~/scheduler/types\";\nimport { ApwSettings } from \"~/scheduler/handlers/utils\";\n\nconst PB_PAGE_DATA_FIELD = /* GraphQL */ `\n {\n id\n }\n`;\n\nconst ERROR_FIELD = /* GraphQL */ `\n {\n code\n data\n message\n }\n`;\n\nconst PUBLISH_MUTATION = /* GraphQL */ `\n mutation PublishPage($id: ID!) {\n pageBuilder {\n publishPage(id: $id) {\n data ${PB_PAGE_DATA_FIELD}\n error ${ERROR_FIELD}\n }\n }\n }\n`;\n\nconst UNPUBLISH_MUTATION = /* GraphQL */ `\n mutation UnpublishPage($id: ID!) {\n pageBuilder {\n unpublishPage(id: $id) {\n data ${PB_PAGE_DATA_FIELD}\n error ${ERROR_FIELD}\n }\n }\n }\n`;\n\ninterface ApplicationGraphQLBodyVariables {\n id: string;\n}\n\nexport class PageBuilderGraphQL extends ApplicationGraphQL {\n public override name = \"apw.scheduler.applicationGraphQL.pageBuilder\";\n\n public override canUse(data: ApwScheduleActionData): boolean {\n return data.type === ApwContentTypes.PAGE;\n }\n\n public override getUrl(): string {\n return `/graphql`;\n }\n\n public override getArn(settings: ApwSettings): string {\n return settings.mainGraphqlFunctionArn;\n }\n\n public override getGraphQLBody(data: ApwScheduleActionData): ApplicationGraphQLBody | null {\n switch (data.action) {\n case ApwScheduleActionTypes.PUBLISH:\n return this.getPublishBody(data);\n case ApwScheduleActionTypes.UNPUBLISH:\n return this.getUnpublishBody(data);\n default:\n return null;\n }\n }\n\n private getPublishBody(\n data: ApwScheduleActionData\n ): ApplicationGraphQLBody<ApplicationGraphQLBodyVariables> {\n return {\n query: PUBLISH_MUTATION,\n variables: {\n id: data.entryId\n }\n };\n }\n\n private getUnpublishBody(\n data: ApwScheduleActionData\n ): ApplicationGraphQLBody<ApplicationGraphQLBodyVariables> {\n return {\n query: UNPUBLISH_MUTATION,\n variables: {\n id: data.entryId\n }\n };\n }\n}\n"],"mappings":";;;;;;;;AAAA;AAKA;AAGA,
|
1
|
+
{"version":3,"names":["_ApplicationGraphQL","require","_types","PB_PAGE_DATA_FIELD","ERROR_FIELD","PUBLISH_MUTATION","UNPUBLISH_MUTATION","PageBuilderGraphQL","ApplicationGraphQL","constructor","args","_defineProperty2","default","canUse","data","type","ApwContentTypes","PAGE","getUrl","getArn","settings","mainGraphqlFunctionArn","getGraphQLBody","action","ApwScheduleActionTypes","PUBLISH","getPublishBody","UNPUBLISH","getUnpublishBody","query","variables","id","entryId","exports"],"sources":["PageBuilderGraphQL.ts"],"sourcesContent":["import {\n ApplicationGraphQL,\n ApplicationGraphQLBody,\n ApwScheduleActionData\n} from \"./ApplicationGraphQL\";\nimport { ApwContentTypes, ApwScheduleActionTypes } from \"~/scheduler/types\";\nimport { ApwSettings } from \"~/scheduler/handlers/utils\";\n\nconst PB_PAGE_DATA_FIELD = /* GraphQL */ `\n {\n id\n }\n`;\n\nconst ERROR_FIELD = /* GraphQL */ `\n {\n code\n data\n message\n }\n`;\n\nconst PUBLISH_MUTATION = /* GraphQL */ `\n mutation PublishPage($id: ID!) {\n pageBuilder {\n publishPage(id: $id) {\n data ${PB_PAGE_DATA_FIELD}\n error ${ERROR_FIELD}\n }\n }\n }\n`;\n\nconst UNPUBLISH_MUTATION = /* GraphQL */ `\n mutation UnpublishPage($id: ID!) {\n pageBuilder {\n unpublishPage(id: $id) {\n data ${PB_PAGE_DATA_FIELD}\n error ${ERROR_FIELD}\n }\n }\n }\n`;\n\ninterface ApplicationGraphQLBodyVariables {\n id: string;\n}\n\nexport class PageBuilderGraphQL extends ApplicationGraphQL {\n public override name = \"apw.scheduler.applicationGraphQL.pageBuilder\";\n\n public override canUse(data: ApwScheduleActionData): boolean {\n return data.type === ApwContentTypes.PAGE;\n }\n\n public override getUrl(): string {\n return `/graphql`;\n }\n\n public override getArn(settings: ApwSettings): string {\n return settings.mainGraphqlFunctionArn;\n }\n\n public override getGraphQLBody(data: ApwScheduleActionData): ApplicationGraphQLBody | null {\n switch (data.action) {\n case ApwScheduleActionTypes.PUBLISH:\n return this.getPublishBody(data);\n case ApwScheduleActionTypes.UNPUBLISH:\n return this.getUnpublishBody(data);\n default:\n return null;\n }\n }\n\n private getPublishBody(\n data: ApwScheduleActionData\n ): ApplicationGraphQLBody<ApplicationGraphQLBodyVariables> {\n return {\n query: PUBLISH_MUTATION,\n variables: {\n id: data.entryId\n }\n };\n }\n\n private getUnpublishBody(\n data: ApwScheduleActionData\n ): ApplicationGraphQLBody<ApplicationGraphQLBodyVariables> {\n return {\n query: UNPUBLISH_MUTATION,\n variables: {\n id: data.entryId\n }\n };\n }\n}\n"],"mappings":";;;;;;;;AAAA,IAAAA,mBAAA,GAAAC,OAAA;AAKA,IAAAC,MAAA,GAAAD,OAAA;AAGA,MAAME,kBAAkB,GAAG,aAAe;AAC1C;AACA;AACA;AACA,CAAC;AAED,MAAMC,WAAW,GAAG,aAAe;AACnC;AACA;AACA;AACA;AACA;AACA,CAAC;AAED,MAAMC,gBAAgB,GAAG,aAAe;AACxC;AACA;AACA;AACA,uBAAuBF,kBAAmB;AAC1C,wBAAwBC,WAAY;AACpC;AACA;AACA;AACA,CAAC;AAED,MAAME,kBAAkB,GAAG,aAAe;AAC1C;AACA;AACA;AACA,uBAAuBH,kBAAmB;AAC1C,wBAAwBC,WAAY;AACpC;AACA;AACA;AACA,CAAC;AAMM,MAAMG,kBAAkB,SAASC,sCAAkB,CAAC;EAAAC,YAAA,GAAAC,IAAA;IAAA,SAAAA,IAAA;IAAA,IAAAC,gBAAA,CAAAC,OAAA,gBAChC,8CAA8C;EAAA;EAErDC,MAAMA,CAACC,IAA2B,EAAW;IACzD,OAAOA,IAAI,CAACC,IAAI,KAAKC,sBAAe,CAACC,IAAI;EAC7C;EAEgBC,MAAMA,CAAA,EAAW;IAC7B,OAAQ,UAAS;EACrB;EAEgBC,MAAMA,CAACC,QAAqB,EAAU;IAClD,OAAOA,QAAQ,CAACC,sBAAsB;EAC1C;EAEgBC,cAAcA,CAACR,IAA2B,EAAiC;IACvF,QAAQA,IAAI,CAACS,MAAM;MACf,KAAKC,6BAAsB,CAACC,OAAO;QAC/B,OAAO,IAAI,CAACC,cAAc,CAACZ,IAAI,CAAC;MACpC,KAAKU,6BAAsB,CAACG,SAAS;QACjC,OAAO,IAAI,CAACC,gBAAgB,CAACd,IAAI,CAAC;MACtC;QACI,OAAO,IAAI;IACnB;EACJ;EAEQY,cAAcA,CAClBZ,IAA2B,EAC4B;IACvD,OAAO;MACHe,KAAK,EAAExB,gBAAgB;MACvByB,SAAS,EAAE;QACPC,EAAE,EAAEjB,IAAI,CAACkB;MACb;IACJ,CAAC;EACL;EAEQJ,gBAAgBA,CACpBd,IAA2B,EAC4B;IACvD,OAAO;MACHe,KAAK,EAAEvB,kBAAkB;MACzBwB,SAAS,EAAE;QACPC,EAAE,EAAEjB,IAAI,CAACkB;MACb;IACJ,CAAC;EACL;AACJ;AAACC,OAAA,CAAA1B,kBAAA,GAAAA,kBAAA"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["createCustomAuth","storageOperations","ContextPlugin","security","hasApwToken","addAuthenticator","token","startsWith","TOKEN_PREFIX","id","tenant","locale","decodeToken","item","get","where","createdBy","addAuthorizer","name"],"sources":["security.ts"],"sourcesContent":["import { ContextPlugin } from \"@webiny/api\";\nimport { CreateApwContextParams } from \"~/scheduler/types\";\nimport { decodeToken, TOKEN_PREFIX } from \"~/scheduler/handlers/utils\";\nimport { ApwContext } from \"~/types\";\n\nexport const createCustomAuth = ({ storageOperations }: CreateApwContextParams) => {\n return new ContextPlugin<ApwContext>(({ security }) => {\n let hasApwToken = false;\n\n security.addAuthenticator(async token => {\n if (!token.startsWith(TOKEN_PREFIX)) {\n return null;\n }\n\n const { id, tenant, locale } = decodeToken(token);\n /**\n * No point in going further if any piece of information is missing.\n */\n if (!id || !tenant || !locale) {\n return null;\n }\n /**\n * We must verify that action we are trying to execute actually exists.\n */\n const item = await storageOperations.get({\n where: {\n id,\n tenant,\n locale\n }\n });\n\n if (!item) {\n return null;\n }\n\n hasApwToken = true;\n\n return item.createdBy;\n });\n\n security.addAuthorizer(async () => {\n if (!hasApwToken) {\n return null;\n }\n return [{ name: \"*\" }];\n });\n });\n};\n"],"mappings":";;;;;;AAAA;AAEA;AAGO,
|
1
|
+
{"version":3,"names":["_api","require","_utils","createCustomAuth","storageOperations","ContextPlugin","security","hasApwToken","addAuthenticator","token","startsWith","TOKEN_PREFIX","id","tenant","locale","decodeToken","item","get","where","createdBy","addAuthorizer","name","exports"],"sources":["security.ts"],"sourcesContent":["import { ContextPlugin } from \"@webiny/api\";\nimport { CreateApwContextParams } from \"~/scheduler/types\";\nimport { decodeToken, TOKEN_PREFIX } from \"~/scheduler/handlers/utils\";\nimport { ApwContext } from \"~/types\";\n\nexport const createCustomAuth = ({ storageOperations }: CreateApwContextParams) => {\n return new ContextPlugin<ApwContext>(({ security }) => {\n let hasApwToken = false;\n\n security.addAuthenticator(async token => {\n if (!token.startsWith(TOKEN_PREFIX)) {\n return null;\n }\n\n const { id, tenant, locale } = decodeToken(token);\n /**\n * No point in going further if any piece of information is missing.\n */\n if (!id || !tenant || !locale) {\n return null;\n }\n /**\n * We must verify that action we are trying to execute actually exists.\n */\n const item = await storageOperations.get({\n where: {\n id,\n tenant,\n locale\n }\n });\n\n if (!item) {\n return null;\n }\n\n hasApwToken = true;\n\n return item.createdBy;\n });\n\n security.addAuthorizer(async () => {\n if (!hasApwToken) {\n return null;\n }\n return [{ name: \"*\" }];\n });\n });\n};\n"],"mappings":";;;;;;AAAA,IAAAA,IAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AAGO,MAAME,gBAAgB,GAAGA,CAAC;EAAEC;AAA0C,CAAC,KAAK;EAC/E,OAAO,IAAIC,kBAAa,CAAa,CAAC;IAAEC;EAAS,CAAC,KAAK;IACnD,IAAIC,WAAW,GAAG,KAAK;IAEvBD,QAAQ,CAACE,gBAAgB,CAAC,MAAMC,KAAK,IAAI;MACrC,IAAI,CAACA,KAAK,CAACC,UAAU,CAACC,mBAAY,CAAC,EAAE;QACjC,OAAO,IAAI;MACf;MAEA,MAAM;QAAEC,EAAE;QAAEC,MAAM;QAAEC;MAAO,CAAC,GAAG,IAAAC,kBAAW,EAACN,KAAK,CAAC;MACjD;AACZ;AACA;MACY,IAAI,CAACG,EAAE,IAAI,CAACC,MAAM,IAAI,CAACC,MAAM,EAAE;QAC3B,OAAO,IAAI;MACf;MACA;AACZ;AACA;MACY,MAAME,IAAI,GAAG,MAAMZ,iBAAiB,CAACa,GAAG,CAAC;QACrCC,KAAK,EAAE;UACHN,EAAE;UACFC,MAAM;UACNC;QACJ;MACJ,CAAC,CAAC;MAEF,IAAI,CAACE,IAAI,EAAE;QACP,OAAO,IAAI;MACf;MAEAT,WAAW,GAAG,IAAI;MAElB,OAAOS,IAAI,CAACG,SAAS;IACzB,CAAC,CAAC;IAEFb,QAAQ,CAACc,aAAa,CAAC,YAAY;MAC/B,IAAI,CAACb,WAAW,EAAE;QACd,OAAO,IAAI;MACf;MACA,OAAO,CAAC;QAAEc,IAAI,EAAE;MAAI,CAAC,CAAC;IAC1B,CAAC,CAAC;EACN,CAAC,CAAC;AACN,CAAC;AAACC,OAAA,CAAAnB,gBAAA,GAAAA,gBAAA"}
|
@@ -12,11 +12,11 @@ var _handlerAws = require("@webiny/handler-aws");
|
|
12
12
|
/**
|
13
13
|
* This logic/file should be moved somewhere else as it is relying on AWS specific stuff.
|
14
14
|
*/
|
15
|
-
let InvocationTypes
|
16
|
-
exports.InvocationTypes = InvocationTypes;
|
17
|
-
(function (InvocationTypes) {
|
15
|
+
let InvocationTypes = /*#__PURE__*/function (InvocationTypes) {
|
18
16
|
InvocationTypes["SCHEDULED"] = "scheduled";
|
19
|
-
|
17
|
+
return InvocationTypes;
|
18
|
+
}({});
|
19
|
+
exports.InvocationTypes = InvocationTypes;
|
20
20
|
const log = console.log;
|
21
21
|
|
22
22
|
/**
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["InvocationTypes","log","console","createScheduleActionLambda","params","cwClient","cloudWatchEventClient","storageOperations","handlers","createRawEventHandler","payload","context","lambdaContext","eventContext","locale","tenant","invocationType","SCHEDULED","executeTask","args","lambdaName","executeAction","handlerClient","currentTask","getCurrentTask","where","nextItem","list","sort","limit","nextTaskDatetime","data","datetime","currentTaskDatetime","isDateTimeInNextCentury","shouldScheduleTask","futureDatetime","moveDateTimeToNextCentury","update","item","input","shouldRestoreDatetime","restoreDateTime","task","scheduleLambdaExecution","invokedFunctionArn","updateCurrentTask","ex","error","JSON","stringify","message","code","scheduleActionHandlerPlugins","config","basePlugins"],"sources":["index.ts"],"sourcesContent":["/**\n * This logic/file should be moved somewhere else as it is relying on AWS specific stuff.\n */\nimport { ApwScheduleActionStorageOperations } from \"~/scheduler/types\";\nimport {\n isDateTimeInNextCentury,\n moveDateTimeToNextCentury,\n shouldRestoreDatetime,\n basePlugins\n} from \"~/scheduler/handlers/utils\";\nimport {\n executeTask,\n shouldScheduleTask,\n restoreDateTime,\n scheduleLambdaExecution\n} from \"./scheduleAction.utils\";\nimport { createRawEventHandler } from \"@webiny/handler-aws\";\n\nexport enum InvocationTypes {\n SCHEDULED = \"scheduled\"\n}\n\nexport interface HandlerArgs {\n datetime: string;\n tenant: string;\n locale: string;\n invocationType?: InvocationTypes;\n futureDatetime?: string;\n}\n\nexport interface Configuration {\n cwClient: any;\n storageOperations: ApwScheduleActionStorageOperations;\n handlers: {\n executeAction: string;\n };\n}\n\nconst log = console.log;\n\n/**\n * Handler that creates a cloudwatch event rule for the schedule action workflow.\n */\nconst createScheduleActionLambda = (params: Configuration) => {\n const { cwClient: cloudWatchEventClient, storageOperations, handlers } = params;\n\n return createRawEventHandler<HandlerArgs>(\n async ({ payload, context, lambdaContext: eventContext }) => {\n try {\n const { locale, tenant, invocationType } = payload;\n /**\n * If invocationType is \"scheduled\", execute the action.\n */\n if (invocationType === InvocationTypes.SCHEDULED) {\n await executeTask({\n args: payload,\n lambdaName: handlers.executeAction,\n handlerClient: context.handlerClient,\n storageOperations\n });\n }\n\n /**\n * Get current scheduled task from the DB.\n */\n const currentTask = await storageOperations.getCurrentTask({\n where: {\n tenant,\n locale\n }\n });\n\n /**\n * Get next task from the DB.\n */\n const [[nextItem]] = await storageOperations.list({\n where: {\n tenant,\n locale\n },\n sort: [\"datetime_ASC\"],\n limit: 1\n });\n\n if (!nextItem) {\n log(`No item found.`);\n return;\n }\n\n const nextTaskDatetime = nextItem.data.datetime;\n const currentTaskDatetime = currentTask && currentTask.data.datetime;\n\n if (isDateTimeInNextCentury(nextTaskDatetime)) {\n log(`Already processed the task.`);\n return;\n }\n\n if (!shouldScheduleTask(nextTaskDatetime, currentTaskDatetime)) {\n log(`Already scheduled the task.`);\n return;\n }\n\n const futureDatetime = moveDateTimeToNextCentury(nextItem.data.datetime);\n /**\n * Update \"datetime\" to a future date to mark it as scheduled.\n */\n log(`Update task's datetime to `, futureDatetime);\n await storageOperations.update({\n item: {\n ...nextItem,\n data: { ...nextItem.data, datetime: futureDatetime }\n },\n input: { ...nextItem.data, datetime: futureDatetime }\n });\n /**\n * Restore \"datetime\" of current task so that it can be schedule in next cycle.\n */\n if (\n currentTaskDatetime &&\n shouldRestoreDatetime({\n invocationType,\n datetime: currentTaskDatetime\n })\n ) {\n await restoreDateTime({\n tenant,\n locale,\n task: currentTask,\n storageOperations\n });\n }\n /**\n * Schedule Lambda\n */\n log(`Schedule Lambda Execution...`);\n await scheduleLambdaExecution({\n cloudWatchEventClient,\n invokedFunctionArn: eventContext.invokedFunctionArn,\n datetime: nextItem.data.datetime,\n futureDatetime: futureDatetime,\n tenant,\n locale\n });\n /**\n * Update current task.\n */\n await storageOperations.updateCurrentTask({ item: nextItem });\n } catch (ex) {\n console.error(\n \"[HANDLER_CREATE_RULE] => \",\n JSON.stringify({\n message: ex.message,\n code: ex.code,\n data: ex.data\n })\n );\n // TODO: Handler error. Maybe save it into DB.\n }\n }\n );\n};\n\nexport const scheduleActionHandlerPlugins = (config: Configuration) => [\n basePlugins(),\n createScheduleActionLambda(config)\n];\n"],"mappings":";;;;;;;;AAIA;AAMA;AAMA;AAhBA;AACA;AACA;AAFA,
|
1
|
+
{"version":3,"names":["_utils","require","_scheduleAction","_handlerAws","InvocationTypes","exports","log","console","createScheduleActionLambda","params","cwClient","cloudWatchEventClient","storageOperations","handlers","createRawEventHandler","payload","context","lambdaContext","eventContext","locale","tenant","invocationType","SCHEDULED","executeTask","args","lambdaName","executeAction","handlerClient","currentTask","getCurrentTask","where","nextItem","list","sort","limit","nextTaskDatetime","data","datetime","currentTaskDatetime","isDateTimeInNextCentury","shouldScheduleTask","futureDatetime","moveDateTimeToNextCentury","update","item","_objectSpread2","default","input","shouldRestoreDatetime","restoreDateTime","task","scheduleLambdaExecution","invokedFunctionArn","updateCurrentTask","ex","error","JSON","stringify","message","code","scheduleActionHandlerPlugins","config","basePlugins"],"sources":["index.ts"],"sourcesContent":["/**\n * This logic/file should be moved somewhere else as it is relying on AWS specific stuff.\n */\nimport { ApwScheduleActionStorageOperations } from \"~/scheduler/types\";\nimport {\n isDateTimeInNextCentury,\n moveDateTimeToNextCentury,\n shouldRestoreDatetime,\n basePlugins\n} from \"~/scheduler/handlers/utils\";\nimport {\n executeTask,\n shouldScheduleTask,\n restoreDateTime,\n scheduleLambdaExecution\n} from \"./scheduleAction.utils\";\nimport { createRawEventHandler } from \"@webiny/handler-aws\";\n\nexport enum InvocationTypes {\n SCHEDULED = \"scheduled\"\n}\n\nexport interface HandlerArgs {\n datetime: string;\n tenant: string;\n locale: string;\n invocationType?: InvocationTypes;\n futureDatetime?: string;\n}\n\nexport interface Configuration {\n cwClient: any;\n storageOperations: ApwScheduleActionStorageOperations;\n handlers: {\n executeAction: string;\n };\n}\n\nconst log = console.log;\n\n/**\n * Handler that creates a cloudwatch event rule for the schedule action workflow.\n */\nconst createScheduleActionLambda = (params: Configuration) => {\n const { cwClient: cloudWatchEventClient, storageOperations, handlers } = params;\n\n return createRawEventHandler<HandlerArgs>(\n async ({ payload, context, lambdaContext: eventContext }) => {\n try {\n const { locale, tenant, invocationType } = payload;\n /**\n * If invocationType is \"scheduled\", execute the action.\n */\n if (invocationType === InvocationTypes.SCHEDULED) {\n await executeTask({\n args: payload,\n lambdaName: handlers.executeAction,\n handlerClient: context.handlerClient,\n storageOperations\n });\n }\n\n /**\n * Get current scheduled task from the DB.\n */\n const currentTask = await storageOperations.getCurrentTask({\n where: {\n tenant,\n locale\n }\n });\n\n /**\n * Get next task from the DB.\n */\n const [[nextItem]] = await storageOperations.list({\n where: {\n tenant,\n locale\n },\n sort: [\"datetime_ASC\"],\n limit: 1\n });\n\n if (!nextItem) {\n log(`No item found.`);\n return;\n }\n\n const nextTaskDatetime = nextItem.data.datetime;\n const currentTaskDatetime = currentTask && currentTask.data.datetime;\n\n if (isDateTimeInNextCentury(nextTaskDatetime)) {\n log(`Already processed the task.`);\n return;\n }\n\n if (!shouldScheduleTask(nextTaskDatetime, currentTaskDatetime)) {\n log(`Already scheduled the task.`);\n return;\n }\n\n const futureDatetime = moveDateTimeToNextCentury(nextItem.data.datetime);\n /**\n * Update \"datetime\" to a future date to mark it as scheduled.\n */\n log(`Update task's datetime to `, futureDatetime);\n await storageOperations.update({\n item: {\n ...nextItem,\n data: { ...nextItem.data, datetime: futureDatetime }\n },\n input: { ...nextItem.data, datetime: futureDatetime }\n });\n /**\n * Restore \"datetime\" of current task so that it can be schedule in next cycle.\n */\n if (\n currentTaskDatetime &&\n shouldRestoreDatetime({\n invocationType,\n datetime: currentTaskDatetime\n })\n ) {\n await restoreDateTime({\n tenant,\n locale,\n task: currentTask,\n storageOperations\n });\n }\n /**\n * Schedule Lambda\n */\n log(`Schedule Lambda Execution...`);\n await scheduleLambdaExecution({\n cloudWatchEventClient,\n invokedFunctionArn: eventContext.invokedFunctionArn,\n datetime: nextItem.data.datetime,\n futureDatetime: futureDatetime,\n tenant,\n locale\n });\n /**\n * Update current task.\n */\n await storageOperations.updateCurrentTask({ item: nextItem });\n } catch (ex) {\n console.error(\n \"[HANDLER_CREATE_RULE] => \",\n JSON.stringify({\n message: ex.message,\n code: ex.code,\n data: ex.data\n })\n );\n // TODO: Handler error. Maybe save it into DB.\n }\n }\n );\n};\n\nexport const scheduleActionHandlerPlugins = (config: Configuration) => [\n basePlugins(),\n createScheduleActionLambda(config)\n];\n"],"mappings":";;;;;;;;AAIA,I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AAE,8BAA6B,CAAC;MACnC,MAAM,IAAA6C,uCAAuB,EAAC;QAC1BxC,qBAAqB;QACrByC,kBAAkB,EAAElC,YAAY,CAACkC,kBAAkB;QACnDf,QAAQ,EAAEN,QAAQ,CAACK,IAAI,CAACC,QAAQ;QAChCI,cAAc,EAAEA,cAAc;QAC9BrB,MAAM;QACND;MACJ,CAAC,CAAC;MACF;AAChB;AACA;MACgB,MAAMP,iBAAiB,CAACyC,iBAAiB,CAAC;QAAET,IAAI,EAAEb;MAAS,CAAC,CAAC;IACjE,CAAC,CAAC,OAAOuB,EAAE,EAAE;MACT/C,OAAO,CAACgD,KAAK,CACT,2BAA2B,EAC3BC,IAAI,CAACC,SAAS,CAAC;QACXC,OAAO,EAAEJ,EAAE,CAACI,OAAO;QACnBC,IAAI,EAAEL,EAAE,CAACK,IAAI;QACbvB,IAAI,EAAEkB,EAAE,CAAClB;MACb,CAAC,CACL,CAAC;MACD;IACJ;EACJ,CACJ,CAAC;AACL,CAAC;;AAEM,MAAMwB,4BAA4B,GAAIC,MAAqB,IAAK,CACnE,IAAAC,kBAAW,EAAC,CAAC,EACbtD,0BAA0B,CAACqD,MAAM,CAAC,CACrC;AAACxD,OAAA,CAAAuD,4BAAA,GAAAA,4BAAA"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["log","console","scheduleLambdaExecution","cloudWatchEventClient","invokedFunctionArn","datetime","futureDatetime","tenant","locale","eventTargetId","eventRuleName","getApwSettings","removeTargetsCommand","RemoveTargetsCommand","Rule","Ids","removeTargetsResponse","send","FailedEntryCount","info","FailedEntries","deleteRuleCommand","DeleteRuleCommand","Name","cronExpression","dateTimeToCronExpression","ruleParams","ScheduleExpression","State","Description","PutRuleCommand","PutTargetsCommand","Targets","Arn","Id","Input","JSON","stringify","invocationType","InvocationTypes","SCHEDULED","shouldScheduleTask","nextTaskDatetime","currentTaskDatetime","restoreDateTime","task","currentTask","storageOperations","id","item","get","where","newDateTime","moveDateTimeToCurrentCentury","data","update","input","executeTask","args","lambdaName","handlerClient","Date","toISOString","invoke","name","payload","await","deleteCurrentTask","e","error"],"sources":["scheduleAction.utils.ts"],"sourcesContent":["import { dateTimeToCronExpression, moveDateTimeToCurrentCentury } from \"~/scheduler/handlers/utils\";\nimport { ApwScheduleAction } from \"~/scheduler/types\";\nimport {\n HandlerArgs,\n InvocationTypes,\n Configuration\n} from \"~/scheduler/handlers/scheduleAction/index\";\nimport {\n DeleteRuleCommand,\n RemoveTargetsCommand,\n PutTargetsCommand,\n PutRuleCommand\n} from \"@aws-sdk/client-cloudwatch-events\";\nimport { ClientContext } from \"@webiny/handler-client/types\";\nimport { getApwSettings } from \"~/scheduler/handlers/utils\";\n\nconst log = console.log;\n\ninterface ScheduleLambdaExecutionParams extends Omit<HandlerArgs, \"invocationType\"> {\n cloudWatchEventClient: any;\n invokedFunctionArn: string;\n}\n\n/**\n * Current API limit/quota for Cloudwatch events is sufficient for now. But, we should watch for it;\n * in case of scheduling becoming the most frequently used feature.\n * https://aws.amazon.com/about-aws/whats-new/2017/07/cloudwatch-events-increases-rules-and-api-requests-limits/\n */\nexport async function scheduleLambdaExecution({\n cloudWatchEventClient,\n invokedFunctionArn,\n datetime,\n futureDatetime,\n tenant,\n locale\n}: ScheduleLambdaExecutionParams) {\n const { eventTargetId, eventRuleName } = await getApwSettings();\n /**\n * Remove the target\n */\n const removeTargetsCommand = new RemoveTargetsCommand({\n Rule: eventRuleName,\n Ids: [eventTargetId]\n });\n const removeTargetsResponse = await cloudWatchEventClient.send(removeTargetsCommand);\n /**\n * Log error.\n */\n if (\n typeof removeTargetsResponse.FailedEntryCount === \"number\" &&\n removeTargetsResponse.FailedEntryCount !== 0\n ) {\n console.info(\"Failed in removing the targets!\");\n console.info(removeTargetsResponse.FailedEntries);\n }\n /**\n * Delete the Rule\n */\n const deleteRuleCommand = new DeleteRuleCommand({\n Name: eventRuleName\n });\n await cloudWatchEventClient.send(deleteRuleCommand);\n\n /**\n * Create a new one.\n * Min H D M DW Y\n * 20 10 10 03 * 2022\n */\n const cronExpression = dateTimeToCronExpression(datetime);\n\n const ruleParams = {\n Name: eventRuleName,\n ScheduleExpression: `cron(${cronExpression})`,\n State: \"ENABLED\",\n Description: `Enable us to schedule an action in publishing workflow at a particular datetime`\n };\n\n await cloudWatchEventClient.send(new PutRuleCommand(ruleParams));\n /**\n * Add lambda as target for the rule.\n */\n await cloudWatchEventClient.send(\n new PutTargetsCommand({\n Rule: eventRuleName,\n Targets: [\n {\n Arn: invokedFunctionArn,\n Id: eventTargetId,\n Input: JSON.stringify({\n datetime: datetime,\n tenant: tenant,\n locale: locale,\n invocationType: InvocationTypes.SCHEDULED,\n futureDatetime: futureDatetime\n } as HandlerArgs)\n }\n ]\n })\n );\n}\n\nexport const shouldScheduleTask = (\n nextTaskDatetime: string,\n currentTaskDatetime: string | null\n): boolean => {\n return !currentTaskDatetime || nextTaskDatetime < currentTaskDatetime;\n};\n\ninterface RestoreDateTimeParams\n extends Pick<Configuration, \"storageOperations\">,\n Pick<HandlerArgs, \"tenant\" | \"locale\"> {\n task: ApwScheduleAction;\n}\n\nexport const restoreDateTime = async ({\n locale,\n tenant,\n task: currentTask,\n storageOperations\n}: RestoreDateTimeParams): Promise<void> => {\n log(`Mark task \"${currentTask.id}\" as undone by restoring original \"datetime\".`);\n const item = await storageOperations.get({\n where: {\n tenant,\n locale,\n id: currentTask.id\n }\n });\n if (item) {\n const newDateTime = moveDateTimeToCurrentCentury(item.data.datetime);\n await storageOperations.update({\n item: {\n ...item,\n data: { ...item.data, datetime: newDateTime }\n },\n input: { ...item.data, datetime: newDateTime }\n });\n }\n};\n\ninterface ExecuteTaskParams\n extends Pick<ClientContext, \"handlerClient\">,\n Pick<Configuration, \"storageOperations\"> {\n args: HandlerArgs;\n lambdaName: string;\n}\n\nexport const executeTask = async ({\n args,\n lambdaName,\n handlerClient,\n storageOperations\n}: ExecuteTaskParams): Promise<void> => {\n log(`Executing task at: `, new Date().toISOString());\n\n if (typeof handlerClient.invoke === \"function\") {\n await handlerClient.invoke({\n name: lambdaName,\n payload: {\n futureDatetime: args.futureDatetime,\n datetime: args.datetime,\n tenant: args.tenant,\n locale: args.locale\n },\n await: false\n });\n } else {\n console.log(`context.handlerClient.invoke is not a function!`);\n }\n\n /**\n * Delete current schedule Task. So that, we can schedule a new one later.\n */\n try {\n await storageOperations.deleteCurrentTask({\n tenant: args.tenant,\n locale: args.locale\n });\n } catch (e) {\n console.error(e);\n }\n};\n"],"mappings":";;;;;;;;;;AAAA;AAEA;AAKA;AASA,
|
1
|
+
{"version":3,"names":["_utils","require","_index","_clientCloudwatchEvents","log","console","scheduleLambdaExecution","cloudWatchEventClient","invokedFunctionArn","datetime","futureDatetime","tenant","locale","eventTargetId","eventRuleName","getApwSettings","removeTargetsCommand","RemoveTargetsCommand","Rule","Ids","removeTargetsResponse","send","FailedEntryCount","info","FailedEntries","deleteRuleCommand","DeleteRuleCommand","Name","cronExpression","dateTimeToCronExpression","ruleParams","ScheduleExpression","State","Description","PutRuleCommand","PutTargetsCommand","Targets","Arn","Id","Input","JSON","stringify","invocationType","InvocationTypes","SCHEDULED","shouldScheduleTask","nextTaskDatetime","currentTaskDatetime","exports","restoreDateTime","task","currentTask","storageOperations","id","item","get","where","newDateTime","moveDateTimeToCurrentCentury","data","update","_objectSpread2","default","input","executeTask","args","lambdaName","handlerClient","Date","toISOString","invoke","name","payload","await","deleteCurrentTask","e","error"],"sources":["scheduleAction.utils.ts"],"sourcesContent":["import { dateTimeToCronExpression, moveDateTimeToCurrentCentury } from \"~/scheduler/handlers/utils\";\nimport { ApwScheduleAction } from \"~/scheduler/types\";\nimport {\n HandlerArgs,\n InvocationTypes,\n Configuration\n} from \"~/scheduler/handlers/scheduleAction/index\";\nimport {\n DeleteRuleCommand,\n RemoveTargetsCommand,\n PutTargetsCommand,\n PutRuleCommand\n} from \"@aws-sdk/client-cloudwatch-events\";\nimport { ClientContext } from \"@webiny/handler-client/types\";\nimport { getApwSettings } from \"~/scheduler/handlers/utils\";\n\nconst log = console.log;\n\ninterface ScheduleLambdaExecutionParams extends Omit<HandlerArgs, \"invocationType\"> {\n cloudWatchEventClient: any;\n invokedFunctionArn: string;\n}\n\n/**\n * Current API limit/quota for Cloudwatch events is sufficient for now. But, we should watch for it;\n * in case of scheduling becoming the most frequently used feature.\n * https://aws.amazon.com/about-aws/whats-new/2017/07/cloudwatch-events-increases-rules-and-api-requests-limits/\n */\nexport async function scheduleLambdaExecution({\n cloudWatchEventClient,\n invokedFunctionArn,\n datetime,\n futureDatetime,\n tenant,\n locale\n}: ScheduleLambdaExecutionParams) {\n const { eventTargetId, eventRuleName } = await getApwSettings();\n /**\n * Remove the target\n */\n const removeTargetsCommand = new RemoveTargetsCommand({\n Rule: eventRuleName,\n Ids: [eventTargetId]\n });\n const removeTargetsResponse = await cloudWatchEventClient.send(removeTargetsCommand);\n /**\n * Log error.\n */\n if (\n typeof removeTargetsResponse.FailedEntryCount === \"number\" &&\n removeTargetsResponse.FailedEntryCount !== 0\n ) {\n console.info(\"Failed in removing the targets!\");\n console.info(removeTargetsResponse.FailedEntries);\n }\n /**\n * Delete the Rule\n */\n const deleteRuleCommand = new DeleteRuleCommand({\n Name: eventRuleName\n });\n await cloudWatchEventClient.send(deleteRuleCommand);\n\n /**\n * Create a new one.\n * Min H D M DW Y\n * 20 10 10 03 * 2022\n */\n const cronExpression = dateTimeToCronExpression(datetime);\n\n const ruleParams = {\n Name: eventRuleName,\n ScheduleExpression: `cron(${cronExpression})`,\n State: \"ENABLED\",\n Description: `Enable us to schedule an action in publishing workflow at a particular datetime`\n };\n\n await cloudWatchEventClient.send(new PutRuleCommand(ruleParams));\n /**\n * Add lambda as target for the rule.\n */\n await cloudWatchEventClient.send(\n new PutTargetsCommand({\n Rule: eventRuleName,\n Targets: [\n {\n Arn: invokedFunctionArn,\n Id: eventTargetId,\n Input: JSON.stringify({\n datetime: datetime,\n tenant: tenant,\n locale: locale,\n invocationType: InvocationTypes.SCHEDULED,\n futureDatetime: futureDatetime\n } as HandlerArgs)\n }\n ]\n })\n );\n}\n\nexport const shouldScheduleTask = (\n nextTaskDatetime: string,\n currentTaskDatetime: string | null\n): boolean => {\n return !currentTaskDatetime || nextTaskDatetime < currentTaskDatetime;\n};\n\ninterface RestoreDateTimeParams\n extends Pick<Configuration, \"storageOperations\">,\n Pick<HandlerArgs, \"tenant\" | \"locale\"> {\n task: ApwScheduleAction;\n}\n\nexport const restoreDateTime = async ({\n locale,\n tenant,\n task: currentTask,\n storageOperations\n}: RestoreDateTimeParams): Promise<void> => {\n log(`Mark task \"${currentTask.id}\" as undone by restoring original \"datetime\".`);\n const item = await storageOperations.get({\n where: {\n tenant,\n locale,\n id: currentTask.id\n }\n });\n if (item) {\n const newDateTime = moveDateTimeToCurrentCentury(item.data.datetime);\n await storageOperations.update({\n item: {\n ...item,\n data: { ...item.data, datetime: newDateTime }\n },\n input: { ...item.data, datetime: newDateTime }\n });\n }\n};\n\ninterface ExecuteTaskParams\n extends Pick<ClientContext, \"handlerClient\">,\n Pick<Configuration, \"storageOperations\"> {\n args: HandlerArgs;\n lambdaName: string;\n}\n\nexport const executeTask = async ({\n args,\n lambdaName,\n handlerClient,\n storageOperations\n}: ExecuteTaskParams): Promise<void> => {\n log(`Executing task at: `, new Date().toISOString());\n\n if (typeof handlerClient.invoke === \"function\") {\n await handlerClient.invoke({\n name: lambdaName,\n payload: {\n futureDatetime: args.futureDatetime,\n datetime: args.datetime,\n tenant: args.tenant,\n locale: args.locale\n },\n await: false\n });\n } else {\n console.log(`context.handlerClient.invoke is not a function!`);\n }\n\n /**\n * Delete current schedule Task. So that, we can schedule a new one later.\n */\n try {\n await storageOperations.deleteCurrentTask({\n tenant: args.tenant,\n locale: args.locale\n });\n } catch (e) {\n console.error(e);\n }\n};\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AAKA,IAAAE,uBAAA,GAAAF,OAAA;AASA,MAAMG,GAA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ESSION","getIsoStringTillMinutes","datetime","isNaN","Date","parse","slice","lastIndexOf","dateTimeToCronExpression","dayOfWeek","format","moveDateTimeToNextCentury","add","toISOString","moveDateTimeToCurrentCentury","subtract","isDateTimeInNextCentury","isAfter","shouldRestoreDatetime","invocationType","selfInvoked","InvocationTypes","SCHEDULED","today","isExecutionPending","encodeToken","id","tenant","locale","TOKEN_PREFIX","decodeToken","token","auth","length","split","documentClient","DocumentClient","convertEmptyValues","region","process","env","AWS_REGION","basePlugins","dynamoDbPlugins","logsPlugins","dbPlugins","table","DB_TABLE","driver","DynamoDbDriver","getApwSettings","variant","STAGED_ROLLOUTS_VARIANT","params","TableName","Key","PK","SK","Item","get","promise","mainGraphqlFunctionArn","eventRuleName","eventTargetId"],"sources":["utils.ts"],"sourcesContent":["import dayjs from \"dayjs\";\nimport utc from \"dayjs/plugin/utc\";\nimport { DocumentClient } from \"aws-sdk/clients/dynamodb\";\nimport dbPlugins from \"@webiny/handler-db\";\nimport { DynamoDbDriver } from \"@webiny/db-dynamodb\";\nimport dynamoDbPlugins from \"@webiny/db-dynamodb/plugins\";\nimport logsPlugins from \"@webiny/handler-logs\";\nimport { InvocationTypes } from \"~/scheduler/types\";\n\n/**\n * https://day.js.org/docs/en/plugin/utc\n */\ndayjs.extend(utc);\n\nconst TIME_SEPARATOR = \":\";\nconst ELAPSED_CRON_EXPRESSION = \"* * * * ? 2000\";\n\nexport const getIsoStringTillMinutes = (datetime: string): string => {\n /**\n * Validate datetime.\n */\n if (isNaN(Date.parse(datetime))) {\n return datetime;\n }\n // input = \"2022-03-08T05:41:13.230Z\"\n // output = \"2022-03-08T05:41\"\n return datetime.slice(0, datetime.lastIndexOf(TIME_SEPARATOR));\n};\n\nexport const dateTimeToCronExpression = (datetime: string): string => {\n if (!datetime) {\n return ELAPSED_CRON_EXPRESSION;\n }\n /**\n * You can't specify the Day-of-month and Day-of-week fields in the same cron expression.\n * If you specify a value (or a *) in one of the fields, you must use a ? (question mark) in the other.\n *\n * https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html\n */\n const dayOfWeek = \"?\";\n\n return dayjs.utc(datetime).format(`mm H D M [${dayOfWeek}] YYYY`);\n};\n\nexport const moveDateTimeToNextCentury = (datetime: string): string => {\n return dayjs.utc(datetime).add(100, \"year\").toISOString();\n};\n\nexport const moveDateTimeToCurrentCentury = (datetime: string): string => {\n return dayjs.utc(datetime).subtract(100, \"year\").toISOString();\n};\n\nexport const isDateTimeInNextCentury = (datetime: string): boolean => {\n return dayjs.utc(datetime).isAfter(\"2100-01-01\", \"year\");\n};\n\ninterface ShouldRestoreDatetimeParams {\n invocationType?: InvocationTypes;\n datetime: string;\n}\n\nexport const shouldRestoreDatetime = ({\n invocationType,\n datetime\n}: ShouldRestoreDatetimeParams): boolean => {\n /**\n * \"invocationType\" will not be SCHEDULED when the lambda is called from Main GQL handler.\n *\n * Which means a new content is scheduled for \"publish\"/\"unpublish\" therefore, we need to restore the previously\n * scheduled action if it has not been executed already.\n */\n const selfInvoked = invocationType === InvocationTypes.SCHEDULED;\n\n const today = dayjs.utc();\n const isExecutionPending = dayjs.utc(datetime).isAfter(today);\n\n return !selfInvoked && isExecutionPending;\n};\n\ninterface EncodeTokenParams {\n id: string;\n tenant: string;\n locale: string;\n}\n\nexport const encodeToken = ({ id, tenant, locale }: EncodeTokenParams) => {\n return `${TOKEN_PREFIX}${id}__${tenant}__${locale}`;\n};\n\nexport const TOKEN_PREFIX = \"apw-\";\n\nexport const decodeToken = (token: string): Partial<EncodeTokenParams> => {\n const auth = token.slice(TOKEN_PREFIX.length);\n const [id, tenant, locale] = auth.split(\"__\");\n\n return {\n id,\n tenant,\n locale\n };\n};\n\nexport const documentClient = new DocumentClient({\n convertEmptyValues: true,\n region: process.env.AWS_REGION\n});\n\nexport const basePlugins = () => [\n dynamoDbPlugins(),\n logsPlugins(),\n dbPlugins({\n table: process.env.DB_TABLE,\n driver: new DynamoDbDriver({\n documentClient\n })\n })\n];\n\n/**\n * Get APW settings record from DDB.\n */\nexport interface ApwSettings {\n mainGraphqlFunctionArn: string;\n eventRuleName: string;\n eventTargetId: string;\n}\n\nexport const getApwSettings = async (): Promise<ApwSettings> => {\n const variant = process.env.STAGED_ROLLOUTS_VARIANT;\n\n const params = {\n TableName: process.env.DB_TABLE as string,\n Key: {\n PK: `APW#SETTINGS`,\n SK: variant || \"default\"\n }\n };\n\n const { Item } = await documentClient.get(params).promise();\n\n return {\n mainGraphqlFunctionArn: Item ? Item[\"mainGraphqlFunctionArn\"] : \"mainGraphqlFunctionArn\",\n eventRuleName: Item ? Item[\"eventRuleName\"] : \"eventRuleName\",\n eventTargetId: Item ? Item[\"eventTargetId\"] : \"eventTargetId\"\n };\n};\n"],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;
|
1
|
+
{"version":3,"names":["_dayjs","_interopRequireDefault","require","_utc","_dynamodb","_handlerDb","_dbDynamodb","_plugins","_handlerLogs","_types","dayjs","extend","utc","TIME_SEPARATOR","ELAPSED_CRON_EXPRESSION","getIsoStringTillMinutes","datetime","isNaN","Date","parse","slice","lastIndexOf","exports","dateTimeToCronExpression","dayOfWeek","format","moveDateTimeToNextCentury","add","toISOString","moveDateTimeToCurrentCentury","subtract","isDateTimeInNextCentury","isAfter","shouldRestoreDatetime","invocationType","selfInvoked","InvocationTypes","SCHEDULED","today","isExecutionPending","encodeToken","id","tenant","locale","TOKEN_PREFIX","decodeToken","token","auth","length","split","documentClient","DocumentClient","convertEmptyValues","region","process","env","AWS_REGION","basePlugins","dynamoDbPlugins","logsPlugins","dbPlugins","table","DB_TABLE","driver","DynamoDbDriver","getApwSettings","variant","STAGED_ROLLOUTS_VARIANT","params","TableName","Key","PK","SK","Item","get","promise","mainGraphqlFunctionArn","eventRuleName","eventTargetId"],"sources":["utils.ts"],"sourcesContent":["import dayjs from \"dayjs\";\nimport utc from \"dayjs/plugin/utc\";\nimport { DocumentClient } from \"aws-sdk/clients/dynamodb\";\nimport dbPlugins from \"@webiny/handler-db\";\nimport { DynamoDbDriver } from \"@webiny/db-dynamodb\";\nimport dynamoDbPlugins from \"@webiny/db-dynamodb/plugins\";\nimport logsPlugins from \"@webiny/handler-logs\";\nimport { InvocationTypes } from \"~/scheduler/types\";\n\n/**\n * https://day.js.org/docs/en/plugin/utc\n */\ndayjs.extend(utc);\n\nconst TIME_SEPARATOR = \":\";\nconst ELAPSED_CRON_EXPRESSION = \"* * * * ? 2000\";\n\nexport const getIsoStringTillMinutes = (datetime: string): string => {\n /**\n * Validate datetime.\n */\n if (isNaN(Date.parse(datetime))) {\n return datetime;\n }\n // input = \"2022-03-08T05:41:13.230Z\"\n // output = \"2022-03-08T05:41\"\n return datetime.slice(0, datetime.lastIndexOf(TIME_SEPARATOR));\n};\n\nexport const dateTimeToCronExpression = (datetime: string): string => {\n if (!datetime) {\n return ELAPSED_CRON_EXPRESSION;\n }\n /**\n * You can't specify the Day-of-month and Day-of-week fields in the same cron expression.\n * If you specify a value (or a *) in one of the fields, you must use a ? (question mark) in the other.\n *\n * https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html\n */\n const dayOfWeek = \"?\";\n\n return dayjs.utc(datetime).format(`mm H D M [${dayOfWeek}] YYYY`);\n};\n\nexport const moveDateTimeToNextCentury = (datetime: string): string => {\n return dayjs.utc(datetime).add(100, \"year\").toISOString();\n};\n\nexport const moveDateTimeToCurrentCentury = (datetime: string): string => {\n return dayjs.utc(datetime).subtract(100, \"year\").toISOString();\n};\n\nexport const isDateTimeInNextCentury = (datetime: string): boolean => {\n return dayjs.utc(datetime).isAfter(\"2100-01-01\", \"year\");\n};\n\ninterface ShouldRestoreDatetimeParams {\n invocationType?: InvocationTypes;\n datetime: string;\n}\n\nexport const shouldRestoreDatetime = ({\n invocationType,\n datetime\n}: ShouldRestoreDatetimeParams): boolean => {\n /**\n * \"invocationType\" will not be SCHEDULED when the lambda is called from Main GQL handler.\n *\n * Which means a new content is scheduled for \"publish\"/\"unpublish\" therefore, we need to restore the previously\n * scheduled action if it has not been executed already.\n */\n const selfInvoked = invocationType === InvocationTypes.SCHEDULED;\n\n const today = dayjs.utc();\n const isExecutionPending = dayjs.utc(datetime).isAfter(today);\n\n return !selfInvoked && isExecutionPending;\n};\n\ninterface EncodeTokenParams {\n id: string;\n tenant: string;\n locale: string;\n}\n\nexport const encodeToken = ({ id, tenant, locale }: EncodeTokenParams) => {\n return `${TOKEN_PREFIX}${id}__${tenant}__${locale}`;\n};\n\nexport const TOKEN_PREFIX = \"apw-\";\n\nexport const decodeToken = (token: string): Partial<EncodeTokenParams> => {\n const auth = token.slice(TOKEN_PREFIX.length);\n const [id, tenant, locale] = auth.split(\"__\");\n\n return {\n id,\n tenant,\n locale\n };\n};\n\nexport const documentClient = new DocumentClient({\n convertEmptyValues: true,\n region: process.env.AWS_REGION\n});\n\nexport const basePlugins = () => [\n dynamoDbPlugins(),\n logsPlugins(),\n dbPlugins({\n table: process.env.DB_TABLE,\n driver: new DynamoDbDriver({\n documentClient\n })\n })\n];\n\n/**\n * Get APW settings record from DDB.\n */\nexport interface ApwSettings {\n mainGraphqlFunctionArn: string;\n eventRuleName: string;\n eventTargetId: string;\n}\n\nexport const getApwSettings = async (): Promise<ApwSettings> => {\n const variant = process.env.STAGED_ROLLOUTS_VARIANT;\n\n const params = {\n TableName: process.env.DB_TABLE as string,\n Key: {\n PK: `APW#SETTINGS`,\n SK: variant || \"default\"\n }\n };\n\n const { Item } = await documentClient.get(params).promise();\n\n return {\n mainGraphqlFunctionArn: Item ? Item[\"mainGraphqlFunctionArn\"] : \"mainGraphqlFunctionArn\",\n eventRuleName: Item ? Item[\"eventRuleName\"] : \"eventRuleName\",\n eventTargetId: Item ? Item[\"eventTargetId\"] : \"eventTargetId\"\n };\n};\n"],"mappings":";;;;;;;AAAA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,IAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAAA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AAI,CAAC,eAAe,CAAC,GAAG;EAClD,CAAC;AACL,CAAC;AAACnD,OAAA,CAAA2C,cAAA,GAAAA,cAAA"}
|
package/scheduler/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["createScheduler","params","getLocale","getIdentity","getTenant","getPermission","storageOperations","createScheduleActionMethods"],"sources":["index.ts"],"sourcesContent":["import { createScheduleActionMethods } from \"./createScheduleActionMethods\";\nimport { ApwScheduleActionCrud, CreateScheduleActionParams } from \"./types\";\n\nexport const createScheduler = (params: CreateScheduleActionParams): ApwScheduleActionCrud => {\n const { getLocale, getIdentity, getTenant, getPermission, storageOperations } = params;\n\n return createScheduleActionMethods({\n getLocale,\n getIdentity,\n getTenant,\n getPermission,\n storageOperations\n });\n};\n"],"mappings":";;;;;;AAAA;AAGO,
|
1
|
+
{"version":3,"names":["_createScheduleActionMethods","require","createScheduler","params","getLocale","getIdentity","getTenant","getPermission","storageOperations","createScheduleActionMethods","exports"],"sources":["index.ts"],"sourcesContent":["import { createScheduleActionMethods } from \"./createScheduleActionMethods\";\nimport { ApwScheduleActionCrud, CreateScheduleActionParams } from \"./types\";\n\nexport const createScheduler = (params: CreateScheduleActionParams): ApwScheduleActionCrud => {\n const { getLocale, getIdentity, getTenant, getPermission, storageOperations } = params;\n\n return createScheduleActionMethods({\n getLocale,\n getIdentity,\n getTenant,\n getPermission,\n storageOperations\n });\n};\n"],"mappings":";;;;;;AAAA,IAAAA,4BAAA,GAAAC,OAAA;AAGO,MAAMC,eAAe,GAAIC,MAAkC,IAA4B;EAC1F,MAAM;IAAEC,SAAS;IAAEC,WAAW;IAAEC,SAAS;IAAEC,aAAa;IAAEC;EAAkB,CAAC,GAAGL,MAAM;EAEtF,OAAO,IAAAM,wDAA2B,EAAC;IAC/BL,SAAS;IACTC,WAAW;IACXC,SAAS;IACTC,aAAa;IACbC;EACJ,CAAC,CAAC;AACN,CAAC;AAACE,OAAA,CAAAR,eAAA,GAAAA,eAAA"}
|
package/scheduler/types.js
CHANGED
@@ -4,20 +4,20 @@ Object.defineProperty(exports, "__esModule", {
|
|
4
4
|
value: true
|
5
5
|
});
|
6
6
|
exports.InvocationTypes = exports.ApwScheduleActionTypes = exports.ApwContentTypes = void 0;
|
7
|
-
let ApwContentTypes
|
8
|
-
exports.ApwContentTypes = ApwContentTypes;
|
9
|
-
(function (ApwContentTypes) {
|
7
|
+
let ApwContentTypes = /*#__PURE__*/function (ApwContentTypes) {
|
10
8
|
ApwContentTypes["PAGE"] = "page";
|
11
9
|
ApwContentTypes["CMS_ENTRY"] = "cms_entry";
|
12
|
-
|
13
|
-
|
14
|
-
exports.
|
15
|
-
|
10
|
+
return ApwContentTypes;
|
11
|
+
}({});
|
12
|
+
exports.ApwContentTypes = ApwContentTypes;
|
13
|
+
let ApwScheduleActionTypes = /*#__PURE__*/function (ApwScheduleActionTypes) {
|
16
14
|
ApwScheduleActionTypes["PUBLISH"] = "publish";
|
17
15
|
ApwScheduleActionTypes["UNPUBLISH"] = "unpublish";
|
18
|
-
|
19
|
-
|
20
|
-
exports.
|
21
|
-
|
16
|
+
return ApwScheduleActionTypes;
|
17
|
+
}({});
|
18
|
+
exports.ApwScheduleActionTypes = ApwScheduleActionTypes;
|
19
|
+
let InvocationTypes = /*#__PURE__*/function (InvocationTypes) {
|
22
20
|
InvocationTypes["SCHEDULED"] = "scheduled";
|
23
|
-
|
21
|
+
return InvocationTypes;
|
22
|
+
}({});
|
23
|
+
exports.InvocationTypes = InvocationTypes;
|
package/scheduler/types.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["ApwContentTypes","ApwScheduleActionTypes","InvocationTypes"],"sources":["types.ts"],"sourcesContent":["import { Context } from \"@webiny/api/types\";\nimport { SecurityIdentity, SecurityPermission } from \"@webiny/api-security/types\";\nimport { I18NLocale, I18NContext } from \"@webiny/api-i18n/types\";\nimport { Tenant } from \"@webiny/api-tenancy/types\";\nimport { TenancyContext } from \"@webiny/api-tenancy/types\";\nimport { ApwIdentity } from \"~/types\";\n\nexport interface ListWhere {\n /**\n * Fields.\n */\n id?: string;\n id_in?: string[];\n id_not?: string;\n id_not_in?: string[];\n /**\n * Who created the entry?\n */\n createdBy?: string;\n createdBy_not?: string;\n createdBy_in?: string[];\n createdBy_not_in?: string[];\n /**\n * By datetime field.\n */\n datetime_startsWith?: string;\n}\n\nexport interface ListParams {\n where: ListWhere;\n sort?: (\"datetime_ASC\" | \"datetime_DESC\")[];\n limit?: number;\n after?: string;\n}\n\nexport interface ListMeta {\n /**\n * A cursor for pagination.\n */\n cursor: string | null;\n /**\n * Is there more items to load?\n */\n hasMoreItems: boolean;\n /**\n * Total count of the items in the storage.\n */\n totalCount: number;\n}\n\nexport enum ApwContentTypes {\n PAGE = \"page\",\n CMS_ENTRY = \"cms_entry\"\n}\n\nexport interface BaseFields {\n id: string;\n createdOn: string;\n savedOn?: string;\n createdBy: ApwIdentity;\n tenant: string;\n locale: string;\n}\n\nexport interface ApwScheduleAction extends BaseFields {\n data: ApwScheduleActionData;\n}\n\nexport enum ApwScheduleActionTypes {\n PUBLISH = \"publish\",\n UNPUBLISH = \"unpublish\"\n}\n\nexport interface ApwScheduleActionData {\n action: ApwScheduleActionTypes;\n type: ApwContentTypes;\n datetime: string;\n entryId: string;\n /**\n * We will add modelId to the data for now.\n * TODO extract in separate package?\n */\n modelId?: string;\n}\n\nexport enum InvocationTypes {\n SCHEDULED = \"scheduled\"\n}\n\ninterface BaseApwCrud<TEntry, TCreateEntryParams, TUpdateEntryParams> {\n get(id: string): Promise<TEntry | null>;\n\n create(data: TCreateEntryParams): Promise<TEntry>;\n\n update(id: string, data: TUpdateEntryParams): Promise<TEntry>;\n\n delete(id: string): Promise<Boolean>;\n}\n\nexport interface ApwScheduleActionCrud\n extends BaseApwCrud<ApwScheduleAction, ApwScheduleActionData, ApwScheduleActionData> {\n list(params: ListParams): Promise<[ApwScheduleAction[], ListMeta]>;\n\n getCurrentTask(): Promise<ApwScheduleAction | null>;\n\n updateCurrentTask(item: ApwScheduleAction): Promise<ApwScheduleAction>;\n\n deleteCurrentTask(): Promise<Boolean>;\n}\n\nexport interface ScheduleActionContext extends Context, I18NContext, TenancyContext {\n scheduleAction: ApwScheduleActionCrud;\n}\n\nexport interface CreateScheduleActionParams {\n getLocale: () => I18NLocale;\n getIdentity: () => SecurityIdentity;\n getTenant: () => Tenant;\n getPermission: (name: string) => Promise<SecurityPermission | null>;\n storageOperations: ApwScheduleActionStorageOperations;\n}\n\ninterface CreateApwScheduleActionParams {\n item: ApwScheduleAction;\n input: ApwScheduleActionData;\n}\n\ninterface StorageOperationsGetParams {\n where: {\n id: string;\n tenant: string;\n locale: string;\n };\n}\n\ninterface StorageOperationsDeleteParams {\n id: string;\n tenant: string;\n locale: string;\n}\n\nexport interface ApwScheduleActionListParams extends ListParams {\n where: ListWhere & {\n tenant: string;\n locale: string;\n };\n}\n\nexport type StorageOperationsGetScheduleActionParams = StorageOperationsGetParams;\n\nexport type StorageOperationsDeleteScheduleActionParams = StorageOperationsDeleteParams;\nexport type StorageOperationsListScheduleActionsParams = ApwScheduleActionListParams;\n\nexport type StorageOperationsCreateScheduleActionParams = CreateApwScheduleActionParams;\n\nexport interface StorageOperationsUpdateScheduleActionParams {\n item: ApwScheduleAction;\n input: ApwScheduleActionData;\n}\n\nexport type StorageOperationsListScheduleActionsResponse = [ApwScheduleAction[], ListMeta];\n\nexport interface StorageOperationsUpdateCurrentTaskParams {\n item: ApwScheduleAction;\n}\n\nexport interface StorageOperationsGetCurrentTaskParams {\n where: Pick<StorageOperationsGetParams[\"where\"], \"tenant\" | \"locale\">;\n}\n\nexport type StorageOperationsDeleteCurrentTaskParams = Pick<\n StorageOperationsDeleteParams,\n \"tenant\" | \"locale\"\n>;\n\nexport interface ApwScheduleActionStorageOperations {\n get(params: StorageOperationsGetScheduleActionParams): Promise<ApwScheduleAction | null>;\n\n list(\n params: StorageOperationsListScheduleActionsParams\n ): Promise<StorageOperationsListScheduleActionsResponse>;\n\n create(params: StorageOperationsCreateScheduleActionParams): Promise<ApwScheduleAction>;\n\n update(params: StorageOperationsUpdateScheduleActionParams): Promise<ApwScheduleAction>;\n\n delete(params: StorageOperationsDeleteScheduleActionParams): Promise<Boolean>;\n\n getCurrentTask(\n params: StorageOperationsGetCurrentTaskParams\n ): Promise<ApwScheduleAction | null>;\n\n updateCurrentTask(params: StorageOperationsUpdateCurrentTaskParams): Promise<ApwScheduleAction>;\n\n deleteCurrentTask(params: StorageOperationsDeleteCurrentTaskParams): Promise<Boolean>;\n}\n\nexport interface CreateApwContextParams {\n storageOperations: ApwScheduleActionStorageOperations;\n}\n"],"mappings":";;;;;;IAkDYA,eAAe
|
1
|
+
{"version":3,"names":["ApwContentTypes","exports","ApwScheduleActionTypes","InvocationTypes"],"sources":["types.ts"],"sourcesContent":["import { Context } from \"@webiny/api/types\";\nimport { SecurityIdentity, SecurityPermission } from \"@webiny/api-security/types\";\nimport { I18NLocale, I18NContext } from \"@webiny/api-i18n/types\";\nimport { Tenant } from \"@webiny/api-tenancy/types\";\nimport { TenancyContext } from \"@webiny/api-tenancy/types\";\nimport { ApwIdentity } from \"~/types\";\n\nexport interface ListWhere {\n /**\n * Fields.\n */\n id?: string;\n id_in?: string[];\n id_not?: string;\n id_not_in?: string[];\n /**\n * Who created the entry?\n */\n createdBy?: string;\n createdBy_not?: string;\n createdBy_in?: string[];\n createdBy_not_in?: string[];\n /**\n * By datetime field.\n */\n datetime_startsWith?: string;\n}\n\nexport interface ListParams {\n where: ListWhere;\n sort?: (\"datetime_ASC\" | \"datetime_DESC\")[];\n limit?: number;\n after?: string;\n}\n\nexport interface ListMeta {\n /**\n * A cursor for pagination.\n */\n cursor: string | null;\n /**\n * Is there more items to load?\n */\n hasMoreItems: boolean;\n /**\n * Total count of the items in the storage.\n */\n totalCount: number;\n}\n\nexport enum ApwContentTypes {\n PAGE = \"page\",\n CMS_ENTRY = \"cms_entry\"\n}\n\nexport interface BaseFields {\n id: string;\n createdOn: string;\n savedOn?: string;\n createdBy: ApwIdentity;\n tenant: string;\n locale: string;\n}\n\nexport interface ApwScheduleAction extends BaseFields {\n data: ApwScheduleActionData;\n}\n\nexport enum ApwScheduleActionTypes {\n PUBLISH = \"publish\",\n UNPUBLISH = \"unpublish\"\n}\n\nexport interface ApwScheduleActionData {\n action: ApwScheduleActionTypes;\n type: ApwContentTypes;\n datetime: string;\n entryId: string;\n /**\n * We will add modelId to the data for now.\n * TODO extract in separate package?\n */\n modelId?: string;\n}\n\nexport enum InvocationTypes {\n SCHEDULED = \"scheduled\"\n}\n\ninterface BaseApwCrud<TEntry, TCreateEntryParams, TUpdateEntryParams> {\n get(id: string): Promise<TEntry | null>;\n\n create(data: TCreateEntryParams): Promise<TEntry>;\n\n update(id: string, data: TUpdateEntryParams): Promise<TEntry>;\n\n delete(id: string): Promise<Boolean>;\n}\n\nexport interface ApwScheduleActionCrud\n extends BaseApwCrud<ApwScheduleAction, ApwScheduleActionData, ApwScheduleActionData> {\n list(params: ListParams): Promise<[ApwScheduleAction[], ListMeta]>;\n\n getCurrentTask(): Promise<ApwScheduleAction | null>;\n\n updateCurrentTask(item: ApwScheduleAction): Promise<ApwScheduleAction>;\n\n deleteCurrentTask(): Promise<Boolean>;\n}\n\nexport interface ScheduleActionContext extends Context, I18NContext, TenancyContext {\n scheduleAction: ApwScheduleActionCrud;\n}\n\nexport interface CreateScheduleActionParams {\n getLocale: () => I18NLocale;\n getIdentity: () => SecurityIdentity;\n getTenant: () => Tenant;\n getPermission: (name: string) => Promise<SecurityPermission | null>;\n storageOperations: ApwScheduleActionStorageOperations;\n}\n\ninterface CreateApwScheduleActionParams {\n item: ApwScheduleAction;\n input: ApwScheduleActionData;\n}\n\ninterface StorageOperationsGetParams {\n where: {\n id: string;\n tenant: string;\n locale: string;\n };\n}\n\ninterface StorageOperationsDeleteParams {\n id: string;\n tenant: string;\n locale: string;\n}\n\nexport interface ApwScheduleActionListParams extends ListParams {\n where: ListWhere & {\n tenant: string;\n locale: string;\n };\n}\n\nexport type StorageOperationsGetScheduleActionParams = StorageOperationsGetParams;\n\nexport type StorageOperationsDeleteScheduleActionParams = StorageOperationsDeleteParams;\nexport type StorageOperationsListScheduleActionsParams = ApwScheduleActionListParams;\n\nexport type StorageOperationsCreateScheduleActionParams = CreateApwScheduleActionParams;\n\nexport interface StorageOperationsUpdateScheduleActionParams {\n item: ApwScheduleAction;\n input: ApwScheduleActionData;\n}\n\nexport type StorageOperationsListScheduleActionsResponse = [ApwScheduleAction[], ListMeta];\n\nexport interface StorageOperationsUpdateCurrentTaskParams {\n item: ApwScheduleAction;\n}\n\nexport interface StorageOperationsGetCurrentTaskParams {\n where: Pick<StorageOperationsGetParams[\"where\"], \"tenant\" | \"locale\">;\n}\n\nexport type StorageOperationsDeleteCurrentTaskParams = Pick<\n StorageOperationsDeleteParams,\n \"tenant\" | \"locale\"\n>;\n\nexport interface ApwScheduleActionStorageOperations {\n get(params: StorageOperationsGetScheduleActionParams): Promise<ApwScheduleAction | null>;\n\n list(\n params: StorageOperationsListScheduleActionsParams\n ): Promise<StorageOperationsListScheduleActionsResponse>;\n\n create(params: StorageOperationsCreateScheduleActionParams): Promise<ApwScheduleAction>;\n\n update(params: StorageOperationsUpdateScheduleActionParams): Promise<ApwScheduleAction>;\n\n delete(params: StorageOperationsDeleteScheduleActionParams): Promise<Boolean>;\n\n getCurrentTask(\n params: StorageOperationsGetCurrentTaskParams\n ): Promise<ApwScheduleAction | null>;\n\n updateCurrentTask(params: StorageOperationsUpdateCurrentTaskParams): Promise<ApwScheduleAction>;\n\n deleteCurrentTask(params: StorageOperationsDeleteCurrentTaskParams): Promise<Boolean>;\n}\n\nexport interface CreateApwContextParams {\n storageOperations: ApwScheduleActionStorageOperations;\n}\n"],"mappings":";;;;;;IAkDYA,eAAe,0BAAfA,eAAe;EAAfA,eAAe;EAAfA,eAAe;EAAA,OAAfA,eAAe;AAAA;AAAAC,OAAA,CAAAD,eAAA,GAAAA,eAAA;AAAA,IAkBfE,sBAAsB,0BAAtBA,sBAAsB;EAAtBA,sBAAsB;EAAtBA,sBAAsB;EAAA,OAAtBA,sBAAsB;AAAA;AAAAD,OAAA,CAAAC,sBAAA,GAAAA,sBAAA;AAAA,IAiBtBC,eAAe,0BAAfA,eAAe;EAAfA,eAAe;EAAA,OAAfA,eAAe;AAAA;AAAAF,OAAA,CAAAE,eAAA,GAAAA,eAAA"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["createChangeRequestStorageOperations","params","cms","getCmsContext","security","getChangeRequestModel","model","withoutAuthorization","getModel","WebinyError","getChangeRequest","id","entry","getEntryById","getFieldValues","fields","baseFields","context","transformers","getTransformer","listChangeRequests","entries","meta","listLatestEntries","where","all","Promise","map","ex","message","code","data","createChangeRequest","createEntry","updateChangeRequest","existingEntry","updateEntry","deleteChangeRequest","deleteEntry"],"sources":["changeRequestStorageOperations.ts"],"sourcesContent":["import { ApwChangeRequestStorageOperations } from \"./types\";\nimport { baseFields, CreateApwStorageOperationsParams } from \"~/storageOperations/index\";\nimport { getFieldValues, getTransformer } from \"~/utils/fieldResolver\";\nimport WebinyError from \"@webiny/error\";\nimport { ApwChangeRequest } from \"~/types\";\n\nexport const createChangeRequestStorageOperations = (\n params: CreateApwStorageOperationsParams\n): ApwChangeRequestStorageOperations => {\n const { cms, getCmsContext, security } = params;\n const getChangeRequestModel = async () => {\n const model = await security.withoutAuthorization(async () => {\n return cms.getModel(\"apwChangeRequestModelDefinition\");\n });\n if (!model) {\n throw new WebinyError(\n \"Could not find `apwChangeRequestModelDefinition` model.\",\n \"MODEL_NOT_FOUND_ERROR\"\n );\n }\n return model;\n };\n const getChangeRequest: ApwChangeRequestStorageOperations[\"getChangeRequest\"] = async ({\n id\n }) => {\n const model = await getChangeRequestModel();\n\n const entry = await security.withoutAuthorization(async () => {\n return cms.getEntryById(model, id);\n });\n return getFieldValues({\n entry,\n fields: baseFields,\n context: getCmsContext(),\n transformers: [getTransformer(model, \"body\")]\n });\n };\n return {\n getChangeRequestModel,\n getChangeRequest,\n async listChangeRequests(params) {\n const model = await getChangeRequestModel();\n\n const [entries, meta] = await security.withoutAuthorization(async () => {\n return cms.listLatestEntries(model, {\n ...params,\n where: {\n ...params.where\n }\n });\n });\n try {\n const all = await Promise.all(\n entries.map(entry =>\n getFieldValues<ApwChangeRequest>({\n entry,\n fields: baseFields,\n context: getCmsContext(),\n transformers: [getTransformer(model, \"body\")]\n })\n )\n );\n return [all, meta];\n } catch (ex) {\n throw new WebinyError(ex.message, ex.code, ex.data);\n }\n },\n async createChangeRequest(params) {\n const model = await getChangeRequestModel();\n\n const entry = await security.withoutAuthorization(async () => {\n return cms.createEntry(model, params.data);\n });\n return getFieldValues({\n entry,\n fields: baseFields,\n context: getCmsContext(),\n transformers: [getTransformer(model, \"body\")]\n });\n },\n async updateChangeRequest(params) {\n const model = await getChangeRequestModel();\n /**\n * We're fetching the existing entry here because we're not accepting \"app\" field as input,\n * but, we still need to retain its value after the \"update\" operation.\n */\n const existingEntry = await getChangeRequest({ id: params.id });\n\n const entry = await security.withoutAuthorization(async () => {\n return cms.updateEntry(model, params.id, {\n ...existingEntry,\n ...params.data\n });\n });\n return getFieldValues({\n entry,\n fields: baseFields,\n context: getCmsContext(),\n transformers: [getTransformer(model, \"body\")]\n });\n },\n async deleteChangeRequest(params) {\n const model = await getChangeRequestModel();\n\n await security.withoutAuthorization(async () => {\n return cms.deleteEntry(model, params.id);\n });\n return true;\n }\n };\n};\n"],"mappings":";;;;;;;;AACA;AACA;AACA;AAGO,
|
1
|
+
{"version":3,"names":["_index","require","_fieldResolver","_error","_interopRequireDefault","createChangeRequestStorageOperations","params","cms","getCmsContext","security","getChangeRequestModel","model","withoutAuthorization","getModel","WebinyError","getChangeRequest","id","entry","getEntryById","getFieldValues","fields","baseFields","context","transformers","getTransformer","listChangeRequests","entries","meta","listLatestEntries","_objectSpread2","default","where","all","Promise","map","ex","message","code","data","createChangeRequest","createEntry","updateChangeRequest","existingEntry","updateEntry","deleteChangeRequest","deleteEntry","exports"],"sources":["changeRequestStorageOperations.ts"],"sourcesContent":["import { ApwChangeRequestStorageOperations } from \"./types\";\nimport { baseFields, CreateApwStorageOperationsParams } from \"~/storageOperations/index\";\nimport { getFieldValues, getTransformer } from \"~/utils/fieldResolver\";\nimport WebinyError from \"@webiny/error\";\nimport { ApwChangeRequest } from \"~/types\";\n\nexport const createChangeRequestStorageOperations = (\n params: CreateApwStorageOperationsParams\n): ApwChangeRequestStorageOperations => {\n const { cms, getCmsContext, security } = params;\n const getChangeRequestModel = async () => {\n const model = await security.withoutAuthorization(async () => {\n return cms.getModel(\"apwChangeRequestModelDefinition\");\n });\n if (!model) {\n throw new WebinyError(\n \"Could not find `apwChangeRequestModelDefinition` model.\",\n \"MODEL_NOT_FOUND_ERROR\"\n );\n }\n return model;\n };\n const getChangeRequest: ApwChangeRequestStorageOperations[\"getChangeRequest\"] = async ({\n id\n }) => {\n const model = await getChangeRequestModel();\n\n const entry = await security.withoutAuthorization(async () => {\n return cms.getEntryById(model, id);\n });\n return getFieldValues({\n entry,\n fields: baseFields,\n context: getCmsContext(),\n transformers: [getTransformer(model, \"body\")]\n });\n };\n return {\n getChangeRequestModel,\n getChangeRequest,\n async listChangeRequests(params) {\n const model = await getChangeRequestModel();\n\n const [entries, meta] = await security.withoutAuthorization(async () => {\n return cms.listLatestEntries(model, {\n ...params,\n where: {\n ...params.where\n }\n });\n });\n try {\n const all = await Promise.all(\n entries.map(entry =>\n getFieldValues<ApwChangeRequest>({\n entry,\n fields: baseFields,\n context: getCmsContext(),\n transformers: [getTransformer(model, \"body\")]\n })\n )\n );\n return [all, meta];\n } catch (ex) {\n throw new WebinyError(ex.message, ex.code, ex.data);\n }\n },\n async createChangeRequest(params) {\n const model = await getChangeRequestModel();\n\n const entry = await security.withoutAuthorization(async () => {\n return cms.createEntry(model, params.data);\n });\n return getFieldValues({\n entry,\n fields: baseFields,\n context: getCmsContext(),\n transformers: [getTransformer(model, \"body\")]\n });\n },\n async updateChangeRequest(params) {\n const model = await getChangeRequestModel();\n /**\n * We're fetching the existing entry here because we're not accepting \"app\" field as input,\n * but, we still need to retain its value after the \"update\" operation.\n */\n const existingEntry = await getChangeRequest({ id: params.id });\n\n const entry = await security.withoutAuthorization(async () => {\n return cms.updateEntry(model, params.id, {\n ...existingEntry,\n ...params.data\n });\n });\n return getFieldValues({\n entry,\n fields: baseFields,\n context: getCmsContext(),\n transformers: [getTransformer(model, \"body\")]\n });\n },\n async deleteChangeRequest(params) {\n const model = await getChangeRequestModel();\n\n await security.withoutAuthorization(async () => {\n return cms.deleteEntry(model, params.id);\n });\n return true;\n }\n };\n};\n"],"mappings":";;;;;;;;AACA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,cAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAC,sBAAA,CAAAH,OAAA;AAGO,MAAMI,oCAAoC,GAC7CC,MAAwC,IACJ;EACpC,MAAM;IAAEC,GAAG;IAAEC,aAAa;IAAEC;EAAS,CAAC,GAAGH,MAAM;EAC/C,MAAMI,qBAAqB,GAAG,MAAAA,CAAA,KAAY;IACtC,MAAMC,KAAK,GAAG,MAAMF,QAAQ,CAACG,oBAAoB,CAAC,YAAY;MAC1D,OAAOL,GAAG,CAACM,QAAQ,CAAC,iCAAiC,CAAC;IAC1D,CAAC,CAAC;IACF,IAAI,CAACF,KAAK,EAAE;MACR,MAAM,IAAIG,cAAW,CACjB,yDAAyD,EACzD,uBACJ,CAAC;IACL;IACA,OAAOH,KAAK;EAChB,CAAC;EACD,MAAMI,gBAAuE,GAAG,MAAAA,CAAO;IACnFC;EACJ,CAAC,KAAK;IACF,MAAML,KAAK,GAAG,MAAMD,qBAAqB,CAAC,CAAC;IAE3C,MAAMO,KAAK,GAAG,MAAMR,QAAQ,CAACG,oBAAoB,CAAC,YAAY;MAC1D,OAAOL,GAAG,CAACW,YAAY,CAACP,KAAK,EAAEK,EAAE,CAAC;IACtC,CAAC,CAAC;IACF,OAAO,IAAAG,6BAAc,EAAC;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