@webiny/api-apw 0.0.0-unstable.5e7233243f → 0.0.0-unstable.611c5af35e
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.d.ts +27 -0
- package/ApwChangeRequestNotification.js +30 -0
- package/ApwChangeRequestNotification.js.map +1 -0
- package/ApwCommentNotification.d.ts +27 -0
- package/ApwCommentNotification.js +30 -0
- package/ApwCommentNotification.js.map +1 -0
- package/ApwContentReviewNotification.d.ts +26 -0
- package/ApwContentReviewNotification.js +30 -0
- package/ApwContentReviewNotification.js.map +1 -0
- package/ApwContentUrlPlugin.d.ts +19 -0
- package/ApwContentUrlPlugin.js +30 -0
- package/ApwContentUrlPlugin.js.map +1 -0
- package/ContentApwSettingsPlugin.js +1 -6
- package/ContentApwSettingsPlugin.js.map +1 -1
- package/crud/createChangeRequestMethods.js +21 -25
- package/crud/createChangeRequestMethods.js.map +1 -1
- package/crud/createCommentMethods.js +21 -26
- package/crud/createCommentMethods.js.map +1 -1
- package/crud/createContentReviewMethods.js +71 -125
- package/crud/createContentReviewMethods.js.map +1 -1
- package/crud/createReviewerMethods.js +21 -26
- package/crud/createReviewerMethods.js.map +1 -1
- package/crud/createWorkflowMethods.d.ts +1 -1
- package/crud/createWorkflowMethods.js +37 -28
- package/crud/createWorkflowMethods.js.map +1 -1
- package/crud/index.js +3 -32
- package/crud/index.js.map +1 -1
- package/crud/utils.js +4 -36
- package/crud/utils.js.map +1 -1
- package/index.d.ts +3 -3
- package/index.js +7 -13
- package/index.js.map +1 -1
- package/package.json +38 -37
- package/plugins/cms/CmsEntryApwSettingsGetterPlugin.js +1 -16
- package/plugins/cms/CmsEntryApwSettingsGetterPlugin.js.map +1 -1
- package/plugins/cms/apwEntryPlugins.js +4 -16
- package/plugins/cms/apwEntryPlugins.js.map +1 -1
- package/plugins/cms/index.js +5 -10
- package/plugins/cms/index.js.map +1 -1
- package/plugins/cms/linkContentReviewToEntry.js +4 -21
- package/plugins/cms/linkContentReviewToEntry.js.map +1 -1
- package/plugins/cms/linkWorkflowToEntry.js +7 -36
- package/plugins/cms/linkWorkflowToEntry.js.map +1 -1
- package/plugins/cms/notifications/changeRequestNotification.d.ts +1 -0
- package/plugins/cms/notifications/changeRequestNotification.js +31 -0
- package/plugins/cms/notifications/changeRequestNotification.js.map +1 -0
- package/plugins/cms/notifications/commentNotification.d.ts +1 -0
- package/plugins/cms/notifications/commentNotification.js +31 -0
- package/plugins/cms/notifications/commentNotification.js.map +1 -0
- package/plugins/cms/notifications/contentReviewNotification.d.ts +1 -0
- package/plugins/cms/notifications/contentReviewNotification.js +31 -0
- package/plugins/cms/notifications/contentReviewNotification.js.map +1 -0
- package/plugins/cms/notifications/contentUrl.d.ts +8 -0
- package/plugins/cms/notifications/contentUrl.js +53 -0
- package/plugins/cms/notifications/contentUrl.js.map +1 -0
- package/plugins/cms/triggerContentReview.js +3 -17
- package/plugins/cms/triggerContentReview.js.map +1 -1
- package/plugins/cms/updateContentReviewStatus.js +10 -32
- package/plugins/cms/updateContentReviewStatus.js.map +1 -1
- package/plugins/cms/utils.js +6 -55
- package/plugins/cms/utils.js.map +1 -1
- package/plugins/context.js +1 -32
- package/plugins/context.js.map +1 -1
- package/plugins/graphql/changeRequest.gql.js +2 -9
- package/plugins/graphql/changeRequest.gql.js.map +1 -1
- package/plugins/graphql/comment.gql.js +2 -9
- package/plugins/graphql/comment.gql.js.map +1 -1
- package/plugins/graphql/contentReview.gql.js +5 -24
- package/plugins/graphql/contentReview.gql.js.map +1 -1
- package/plugins/graphql/reviewer.gql.js +4 -9
- package/plugins/graphql/reviewer.gql.js.map +1 -1
- package/plugins/graphql/workflow.gql.js +2 -9
- package/plugins/graphql/workflow.gql.js.map +1 -1
- package/plugins/graphql.js +2 -17
- package/plugins/graphql.js.map +1 -1
- package/plugins/hooks/createReviewerFromIdentity.js +26 -15
- package/plugins/hooks/createReviewerFromIdentity.js.map +1 -1
- package/plugins/hooks/deleteChangeRequestsAfterContentReview.js +2 -10
- package/plugins/hooks/deleteChangeRequestsAfterContentReview.js.map +1 -1
- package/plugins/hooks/deleteCommentsAfterChangeRequest.js +2 -9
- package/plugins/hooks/deleteCommentsAfterChangeRequest.js.map +1 -1
- package/plugins/hooks/index.js +4 -12
- package/plugins/hooks/index.js.map +1 -1
- package/plugins/hooks/initializeContentReviewSteps.js +7 -23
- package/plugins/hooks/initializeContentReviewSteps.js.map +1 -1
- package/plugins/hooks/initializeNotifications.d.ts +2 -0
- package/plugins/hooks/initializeNotifications.js +15 -0
- package/plugins/hooks/initializeNotifications.js.map +1 -0
- package/plugins/hooks/listContentReviews.d.ts +10 -0
- package/plugins/hooks/listContentReviews.js +56 -0
- package/plugins/hooks/listContentReviews.js.map +1 -0
- package/plugins/hooks/notifications/appUrl.d.ts +2 -0
- package/plugins/hooks/notifications/appUrl.js +18 -0
- package/plugins/hooks/notifications/appUrl.js.map +1 -0
- package/plugins/hooks/notifications/changeRequestAfterCreate.d.ts +2 -0
- package/plugins/hooks/notifications/changeRequestAfterCreate.js +116 -0
- package/plugins/hooks/notifications/changeRequestAfterCreate.js.map +1 -0
- package/plugins/hooks/notifications/changeRequestUrl.d.ts +8 -0
- package/plugins/hooks/notifications/changeRequestUrl.js +27 -0
- package/plugins/hooks/notifications/changeRequestUrl.js.map +1 -0
- package/plugins/hooks/notifications/commentAfterCreate.d.ts +2 -0
- package/plugins/hooks/notifications/commentAfterCreate.js +127 -0
- package/plugins/hooks/notifications/commentAfterCreate.js.map +1 -0
- package/plugins/hooks/notifications/commentUrl.d.ts +8 -0
- package/plugins/hooks/notifications/commentUrl.js +27 -0
- package/plugins/hooks/notifications/commentUrl.js.map +1 -0
- package/plugins/hooks/notifications/contentReviewAfterCreate.d.ts +2 -0
- package/plugins/hooks/notifications/contentReviewAfterCreate.js +99 -0
- package/plugins/hooks/notifications/contentReviewAfterCreate.js.map +1 -0
- package/plugins/hooks/notifications/contentReviewUrl.d.ts +7 -0
- package/plugins/hooks/notifications/contentReviewUrl.js +26 -0
- package/plugins/hooks/notifications/contentReviewUrl.js.map +1 -0
- package/plugins/hooks/notifications/contentUrl.d.ts +7 -0
- package/plugins/hooks/notifications/contentUrl.js +24 -0
- package/plugins/hooks/notifications/contentUrl.js.map +1 -0
- package/plugins/hooks/notifications/lastChangeRequestNotificationPlugin.d.ts +11 -0
- package/plugins/hooks/notifications/lastChangeRequestNotificationPlugin.js +21 -0
- package/plugins/hooks/notifications/lastChangeRequestNotificationPlugin.js.map +1 -0
- package/plugins/hooks/notifications/lastCommentNotificationPlugin.d.ts +11 -0
- package/plugins/hooks/notifications/lastCommentNotificationPlugin.js +21 -0
- package/plugins/hooks/notifications/lastCommentNotificationPlugin.js.map +1 -0
- package/plugins/hooks/notifications/lastContentReviewNotificationPlugin.d.ts +11 -0
- package/plugins/hooks/notifications/lastContentReviewNotificationPlugin.js +21 -0
- package/plugins/hooks/notifications/lastContentReviewNotificationPlugin.js.map +1 -0
- package/plugins/hooks/notifications/reviewers.d.ts +15 -0
- package/plugins/hooks/notifications/reviewers.js +44 -0
- package/plugins/hooks/notifications/reviewers.js.map +1 -0
- package/plugins/hooks/notifications/sendChangeRequestNotification.d.ts +2 -0
- package/plugins/hooks/notifications/sendChangeRequestNotification.js +41 -0
- package/plugins/hooks/notifications/sendChangeRequestNotification.js.map +1 -0
- package/plugins/hooks/notifications/sendCommentNotification.d.ts +2 -0
- package/plugins/hooks/notifications/sendCommentNotification.js +41 -0
- package/plugins/hooks/notifications/sendCommentNotification.js.map +1 -0
- package/plugins/hooks/notifications/sendContentReviewNotification.d.ts +2 -0
- package/plugins/hooks/notifications/sendContentReviewNotification.js +41 -0
- package/plugins/hooks/notifications/sendContentReviewNotification.js.map +1 -0
- package/plugins/hooks/updatePendingChangeRequests.js +7 -19
- package/plugins/hooks/updatePendingChangeRequests.js.map +1 -1
- package/plugins/hooks/updateTotalComments.js +14 -27
- package/plugins/hooks/updateTotalComments.js.map +1 -1
- package/plugins/hooks/validateChangeRequest.js +27 -18
- package/plugins/hooks/validateChangeRequest.js.map +1 -1
- package/plugins/hooks/validateComment.js +13 -14
- package/plugins/hooks/validateComment.js.map +1 -1
- package/plugins/hooks/validateContentReview.js +2 -8
- package/plugins/hooks/validateContentReview.js.map +1 -1
- package/plugins/pageBuilder/PageApwSettingsGetterPlugin.js +1 -16
- package/plugins/pageBuilder/PageApwSettingsGetterPlugin.js.map +1 -1
- package/plugins/pageBuilder/apwContentPagePlugins.js +0 -4
- package/plugins/pageBuilder/apwContentPagePlugins.js.map +1 -1
- package/plugins/pageBuilder/extendPbPageSettingsSchema.js +1 -6
- package/plugins/pageBuilder/extendPbPageSettingsSchema.js.map +1 -1
- package/plugins/pageBuilder/index.js +5 -8
- package/plugins/pageBuilder/index.js.map +1 -1
- package/plugins/pageBuilder/linkContentReviewToPage.js +38 -42
- package/plugins/pageBuilder/linkContentReviewToPage.js.map +1 -1
- package/plugins/pageBuilder/linkWorkflowToPage.js +14 -32
- package/plugins/pageBuilder/linkWorkflowToPage.js.map +1 -1
- package/plugins/pageBuilder/notifications/changeRequestNotification.d.ts +1 -0
- package/plugins/pageBuilder/notifications/changeRequestNotification.js +31 -0
- package/plugins/pageBuilder/notifications/changeRequestNotification.js.map +1 -0
- package/plugins/pageBuilder/notifications/commentNotification.d.ts +1 -0
- package/plugins/pageBuilder/notifications/commentNotification.js +31 -0
- package/plugins/pageBuilder/notifications/commentNotification.js.map +1 -0
- package/plugins/pageBuilder/notifications/contentReviewNotification.d.ts +1 -0
- package/plugins/pageBuilder/notifications/contentReviewNotification.js +31 -0
- package/plugins/pageBuilder/notifications/contentReviewNotification.js.map +1 -0
- package/plugins/pageBuilder/notifications/contentUrl.d.ts +1 -0
- package/plugins/pageBuilder/notifications/contentUrl.js +47 -0
- package/plugins/pageBuilder/notifications/contentUrl.js.map +1 -0
- package/plugins/pageBuilder/triggerContentReview.js +3 -14
- package/plugins/pageBuilder/triggerContentReview.js.map +1 -1
- package/plugins/pageBuilder/updateContentReviewStatus.js +10 -26
- package/plugins/pageBuilder/updateContentReviewStatus.js.map +1 -1
- package/plugins/pageBuilder/utils.js +2 -36
- package/plugins/pageBuilder/utils.js.map +1 -1
- package/plugins/utils.d.ts +1 -1
- package/plugins/utils.js +4 -57
- package/plugins/utils.js.map +1 -1
- package/scheduler/createScheduleActionMethods.js +17 -33
- package/scheduler/createScheduleActionMethods.js.map +1 -1
- package/scheduler/handlers/executeAction/index.js +9 -33
- package/scheduler/handlers/executeAction/index.js.map +1 -1
- package/scheduler/handlers/executeAction/plugins/ApplicationGraphQL.js +1 -6
- package/scheduler/handlers/executeAction/plugins/ApplicationGraphQL.js.map +1 -1
- package/scheduler/handlers/executeAction/plugins/HeadlessCMSGraphQL.js +1 -22
- package/scheduler/handlers/executeAction/plugins/HeadlessCMSGraphQL.js.map +1 -1
- package/scheduler/handlers/executeAction/plugins/PageBuilderGraphQL.js +5 -28
- package/scheduler/handlers/executeAction/plugins/PageBuilderGraphQL.js.map +1 -1
- package/scheduler/handlers/executeAction/security.js +0 -11
- package/scheduler/handlers/executeAction/security.js.map +1 -1
- package/scheduler/handlers/scheduleAction/index.js +13 -34
- package/scheduler/handlers/scheduleAction/index.js.map +1 -1
- package/scheduler/handlers/scheduleAction/scheduleAction.utils.js +7 -32
- package/scheduler/handlers/scheduleAction/scheduleAction.utils.js.map +1 -1
- package/scheduler/handlers/utils.js +4 -41
- package/scheduler/handlers/utils.js.map +1 -1
- package/scheduler/index.js +0 -3
- package/scheduler/index.js.map +1 -1
- package/scheduler/types.js +0 -6
- package/scheduler/types.js.map +1 -1
- package/storageOperations/changeRequestStorageOperations.js +5 -28
- package/storageOperations/changeRequestStorageOperations.js.map +1 -1
- package/storageOperations/commentStorageOperations.js +4 -29
- package/storageOperations/commentStorageOperations.js.map +1 -1
- package/storageOperations/contentReviewStorageOperations.js +5 -26
- package/storageOperations/contentReviewStorageOperations.js.map +1 -1
- package/storageOperations/index.js +5 -23
- package/storageOperations/index.js.map +1 -1
- package/storageOperations/models/changeRequest.model.js +0 -9
- package/storageOperations/models/changeRequest.model.js.map +1 -1
- package/storageOperations/models/comment.model.js +0 -8
- package/storageOperations/models/comment.model.js.map +1 -1
- package/storageOperations/models/contentModelPluginFactory.js +3 -12
- package/storageOperations/models/contentModelPluginFactory.js.map +1 -1
- package/storageOperations/models/contentReview.model.js +6 -31
- package/storageOperations/models/contentReview.model.js.map +1 -1
- package/storageOperations/models/index.js +3 -25
- package/storageOperations/models/index.js.map +1 -1
- package/storageOperations/models/reviewer.model.js +17 -9
- package/storageOperations/models/reviewer.model.js.map +1 -1
- package/storageOperations/models/utils.js +3 -6
- package/storageOperations/models/utils.js.map +1 -1
- package/storageOperations/models/workflow.model.js +0 -23
- package/storageOperations/models/workflow.model.js.map +1 -1
- package/storageOperations/reviewerStorageOperations.js +16 -29
- package/storageOperations/reviewerStorageOperations.js.map +1 -1
- package/storageOperations/workflowStorageOperations.js +6 -31
- package/storageOperations/workflowStorageOperations.js.map +1 -1
- package/types.d.ts +99 -84
- package/types.js +0 -14
- package/types.js.map +1 -1
- package/utils/contentApwSettingsPlugin.js +0 -6
- package/utils/contentApwSettingsPlugin.js.map +1 -1
- package/utils/errors.js +1 -18
- package/utils/errors.js.map +1 -1
- package/utils/fieldResolver.js +5 -21
- package/utils/fieldResolver.js.map +1 -1
- package/utils/resolve.js +0 -3
- package/utils/resolve.js.map +1 -1
@@ -1,36 +1,27 @@
|
|
1
1
|
"use strict";
|
2
2
|
|
3
|
-
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
4
|
-
|
3
|
+
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
|
5
4
|
Object.defineProperty(exports, "__esModule", {
|
6
5
|
value: true
|
7
6
|
});
|
8
7
|
exports.scheduleActionHandlerPlugins = exports.InvocationTypes = void 0;
|
9
|
-
|
10
|
-
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
|
11
|
-
|
8
|
+
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
|
12
9
|
var _utils = require("../utils");
|
13
|
-
|
14
10
|
var _scheduleAction = require("./scheduleAction.utils");
|
15
|
-
|
16
11
|
var _handlerAws = require("@webiny/handler-aws");
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
|
21
|
-
|
12
|
+
/**
|
13
|
+
* This logic/file should be moved somewhere else as it is relying on AWS specific stuff.
|
14
|
+
*/
|
22
15
|
let InvocationTypes;
|
23
16
|
exports.InvocationTypes = InvocationTypes;
|
24
|
-
|
25
17
|
(function (InvocationTypes) {
|
26
18
|
InvocationTypes["SCHEDULED"] = "scheduled";
|
27
19
|
})(InvocationTypes || (exports.InvocationTypes = InvocationTypes = {}));
|
28
|
-
|
29
20
|
const log = console.log;
|
21
|
+
|
30
22
|
/**
|
31
23
|
* Handler that creates a cloudwatch event rule for the schedule action workflow.
|
32
24
|
*/
|
33
|
-
|
34
25
|
const createScheduleActionLambda = params => {
|
35
26
|
const {
|
36
27
|
cwClient: cloudWatchEventClient,
|
@@ -51,7 +42,6 @@ const createScheduleActionLambda = params => {
|
|
51
42
|
/**
|
52
43
|
* If invocationType is "scheduled", execute the action.
|
53
44
|
*/
|
54
|
-
|
55
45
|
if (invocationType === InvocationTypes.SCHEDULED) {
|
56
46
|
await (0, _scheduleAction.executeTask)({
|
57
47
|
args: payload,
|
@@ -60,21 +50,20 @@ const createScheduleActionLambda = params => {
|
|
60
50
|
storageOperations
|
61
51
|
});
|
62
52
|
}
|
53
|
+
|
63
54
|
/**
|
64
55
|
* Get current scheduled task from the DB.
|
65
56
|
*/
|
66
|
-
|
67
|
-
|
68
57
|
const currentTask = await storageOperations.getCurrentTask({
|
69
58
|
where: {
|
70
59
|
tenant,
|
71
60
|
locale
|
72
61
|
}
|
73
62
|
});
|
63
|
+
|
74
64
|
/**
|
75
65
|
* Get next task from the DB.
|
76
66
|
*/
|
77
|
-
|
78
67
|
const [[nextItem]] = await storageOperations.list({
|
79
68
|
where: {
|
80
69
|
tenant,
|
@@ -83,45 +72,38 @@ const createScheduleActionLambda = params => {
|
|
83
72
|
sort: ["datetime_ASC"],
|
84
73
|
limit: 1
|
85
74
|
});
|
86
|
-
|
87
75
|
if (!nextItem) {
|
88
76
|
log(`No item found.`);
|
89
77
|
return;
|
90
78
|
}
|
91
|
-
|
92
79
|
const nextTaskDatetime = nextItem.data.datetime;
|
93
80
|
const currentTaskDatetime = currentTask && currentTask.data.datetime;
|
94
|
-
|
95
81
|
if ((0, _utils.isDateTimeInNextCentury)(nextTaskDatetime)) {
|
96
82
|
log(`Already processed the task.`);
|
97
83
|
return;
|
98
84
|
}
|
99
|
-
|
100
85
|
if (!(0, _scheduleAction.shouldScheduleTask)(nextTaskDatetime, currentTaskDatetime)) {
|
101
86
|
log(`Already scheduled the task.`);
|
102
87
|
return;
|
103
88
|
}
|
104
|
-
|
105
89
|
const futureDatetime = (0, _utils.moveDateTimeToNextCentury)(nextItem.data.datetime);
|
106
90
|
/**
|
107
91
|
* Update "datetime" to a future date to mark it as scheduled.
|
108
92
|
*/
|
109
|
-
|
110
93
|
log(`Update task's datetime to `, futureDatetime);
|
111
94
|
await storageOperations.update({
|
112
|
-
item:
|
113
|
-
data:
|
95
|
+
item: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, nextItem), {}, {
|
96
|
+
data: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, nextItem.data), {}, {
|
114
97
|
datetime: futureDatetime
|
115
98
|
})
|
116
99
|
}),
|
117
|
-
input:
|
100
|
+
input: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, nextItem.data), {}, {
|
118
101
|
datetime: futureDatetime
|
119
102
|
})
|
120
103
|
});
|
121
104
|
/**
|
122
105
|
* Restore "datetime" of current task so that it can be schedule in next cycle.
|
123
106
|
*/
|
124
|
-
|
125
107
|
if (currentTaskDatetime && (0, _utils.shouldRestoreDatetime)({
|
126
108
|
invocationType,
|
127
109
|
datetime: currentTaskDatetime
|
@@ -136,8 +118,6 @@ const createScheduleActionLambda = params => {
|
|
136
118
|
/**
|
137
119
|
* Schedule Lambda
|
138
120
|
*/
|
139
|
-
|
140
|
-
|
141
121
|
log(`Schedule Lambda Execution...`);
|
142
122
|
await (0, _scheduleAction.scheduleLambdaExecution)({
|
143
123
|
cloudWatchEventClient,
|
@@ -150,16 +130,15 @@ const createScheduleActionLambda = params => {
|
|
150
130
|
/**
|
151
131
|
* Update current task.
|
152
132
|
*/
|
153
|
-
|
154
133
|
await storageOperations.updateCurrentTask({
|
155
134
|
item: nextItem
|
156
135
|
});
|
157
136
|
} catch (ex) {
|
158
|
-
log("[HANDLER_CREATE_RULE] Error => ", ex);
|
137
|
+
log("[HANDLER_CREATE_RULE] Error => ", ex);
|
138
|
+
// TODO: Handler error. Maybe save it into DB.
|
159
139
|
}
|
160
140
|
});
|
161
141
|
};
|
162
142
|
|
163
143
|
const scheduleActionHandlerPlugins = config => [(0, _utils.basePlugins)(), createScheduleActionLambda(config)];
|
164
|
-
|
165
144
|
exports.scheduleActionHandlerPlugins = scheduleActionHandlerPlugins;
|
@@ -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","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 log(\"[HANDLER_CREATE_RULE] Error => \", ex);\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":"
|
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","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 log(\"[HANDLER_CREATE_RULE] Error => \", ex);\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,IAkBYA,eAAe;AAAA;AAAA,WAAfA,eAAe;EAAfA,eAAe;AAAA,GAAfA,eAAe,+BAAfA,eAAe;AAoB3B,MAAMC,GAAG,GAAGC,OAAO,CAACD,GAAG;;AAEvB;AACA;AACA;AACA,MAAME,0BAA0B,GAAIC,MAAqB,IAAK;EAC1D,MAAM;IAAEC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AqB,IAAK,CACnE,IAAAC,kBAAW,GAAE,EACb/C,0BAA0B,CAAC8C,MAAM,CAAC,CACrC;AAAC"}
|
@@ -1,28 +1,17 @@
|
|
1
1
|
"use strict";
|
2
2
|
|
3
|
-
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
4
|
-
|
3
|
+
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
|
5
4
|
Object.defineProperty(exports, "__esModule", {
|
6
5
|
value: true
|
7
6
|
});
|
8
7
|
exports.restoreDateTime = exports.executeTask = void 0;
|
9
8
|
exports.scheduleLambdaExecution = scheduleLambdaExecution;
|
10
9
|
exports.shouldScheduleTask = void 0;
|
11
|
-
|
12
|
-
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
|
13
|
-
|
10
|
+
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
|
14
11
|
var _utils = require("../utils");
|
15
|
-
|
16
12
|
var _index = require("./index");
|
17
|
-
|
18
13
|
var _clientCloudwatchEvents = require("@aws-sdk/client-cloudwatch-events");
|
19
|
-
|
20
|
-
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
|
21
|
-
|
22
|
-
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
|
23
|
-
|
24
14
|
const log = console.log;
|
25
|
-
|
26
15
|
/**
|
27
16
|
* Current API limit/quota for Cloudwatch events is sufficient for now. But, we should watch for it;
|
28
17
|
* in case of scheduling becoming the most frequently used feature.
|
@@ -43,7 +32,6 @@ async function scheduleLambdaExecution({
|
|
43
32
|
/**
|
44
33
|
* Remove the target
|
45
34
|
*/
|
46
|
-
|
47
35
|
const removeTargetsCommand = new _clientCloudwatchEvents.RemoveTargetsCommand({
|
48
36
|
Rule: eventRuleName,
|
49
37
|
Ids: [eventTargetId]
|
@@ -52,7 +40,6 @@ async function scheduleLambdaExecution({
|
|
52
40
|
/**
|
53
41
|
* Log error.
|
54
42
|
*/
|
55
|
-
|
56
43
|
if (typeof removeTargetsResponse.FailedEntryCount === "number" && removeTargetsResponse.FailedEntryCount !== 0) {
|
57
44
|
console.info("Failed in removing the targets!");
|
58
45
|
console.info(removeTargetsResponse.FailedEntries);
|
@@ -60,18 +47,16 @@ async function scheduleLambdaExecution({
|
|
60
47
|
/**
|
61
48
|
* Delete the Rule
|
62
49
|
*/
|
63
|
-
|
64
|
-
|
65
50
|
const deleteRuleCommand = new _clientCloudwatchEvents.DeleteRuleCommand({
|
66
51
|
Name: eventRuleName
|
67
52
|
});
|
68
53
|
await cloudWatchEventClient.send(deleteRuleCommand);
|
54
|
+
|
69
55
|
/**
|
70
56
|
* Create a new one.
|
71
57
|
* Min H D M DW Y
|
72
58
|
* 20 10 10 03 * 2022
|
73
59
|
*/
|
74
|
-
|
75
60
|
const cronExpression = (0, _utils.dateTimeToCronExpression)(datetime);
|
76
61
|
const ruleParams = {
|
77
62
|
Name: eventRuleName,
|
@@ -83,7 +68,6 @@ async function scheduleLambdaExecution({
|
|
83
68
|
/**
|
84
69
|
* Add lambda as target for the rule.
|
85
70
|
*/
|
86
|
-
|
87
71
|
await cloudWatchEventClient.send(new _clientCloudwatchEvents.PutTargetsCommand({
|
88
72
|
Rule: eventRuleName,
|
89
73
|
Targets: [{
|
@@ -99,13 +83,10 @@ async function scheduleLambdaExecution({
|
|
99
83
|
}]
|
100
84
|
}));
|
101
85
|
}
|
102
|
-
|
103
86
|
const shouldScheduleTask = (nextTaskDatetime, currentTaskDatetime) => {
|
104
87
|
return !currentTaskDatetime || nextTaskDatetime < currentTaskDatetime;
|
105
88
|
};
|
106
|
-
|
107
89
|
exports.shouldScheduleTask = shouldScheduleTask;
|
108
|
-
|
109
90
|
const restoreDateTime = async ({
|
110
91
|
locale,
|
111
92
|
tenant,
|
@@ -120,24 +101,21 @@ const restoreDateTime = async ({
|
|
120
101
|
id: currentTask.id
|
121
102
|
}
|
122
103
|
});
|
123
|
-
|
124
104
|
if (item) {
|
125
105
|
const newDateTime = (0, _utils.moveDateTimeToCurrentCentury)(item.data.datetime);
|
126
106
|
await storageOperations.update({
|
127
|
-
item:
|
128
|
-
data:
|
107
|
+
item: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, item), {}, {
|
108
|
+
data: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, item.data), {}, {
|
129
109
|
datetime: newDateTime
|
130
110
|
})
|
131
111
|
}),
|
132
|
-
input:
|
112
|
+
input: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, item.data), {}, {
|
133
113
|
datetime: newDateTime
|
134
114
|
})
|
135
115
|
});
|
136
116
|
}
|
137
117
|
};
|
138
|
-
|
139
118
|
exports.restoreDateTime = restoreDateTime;
|
140
|
-
|
141
119
|
const executeTask = async ({
|
142
120
|
args,
|
143
121
|
lambdaName,
|
@@ -145,7 +123,6 @@ const executeTask = async ({
|
|
145
123
|
storageOperations
|
146
124
|
}) => {
|
147
125
|
log(`Executing task at: `, new Date().toISOString());
|
148
|
-
|
149
126
|
if (typeof handlerClient.invoke === "function") {
|
150
127
|
await handlerClient.invoke({
|
151
128
|
name: lambdaName,
|
@@ -158,11 +135,10 @@ const executeTask = async ({
|
|
158
135
|
await: false
|
159
136
|
});
|
160
137
|
}
|
138
|
+
|
161
139
|
/**
|
162
140
|
* Delete current schedule Task. So that, we can schedule a new one later.
|
163
141
|
*/
|
164
|
-
|
165
|
-
|
166
142
|
try {
|
167
143
|
await storageOperations.deleteCurrentTask({
|
168
144
|
tenant: args.tenant,
|
@@ -172,5 +148,4 @@ const executeTask = async ({
|
|
172
148
|
console.error(e);
|
173
149
|
}
|
174
150
|
};
|
175
|
-
|
176
151
|
exports.executeTask = executeTask;
|
@@ -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 }\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":"
|
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 }\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,MAAMA,GAAG,GAAGC,OAAO,CAACD,GAAG;AAOvB;AACA;AACA;AACA;AACA;AACO,eAAeE,uBAAuB,CAAC;EAC1CC,qBAAqB;EACrBC,kBAAkB;EAClBC,QAAQ;EACRC,cAAc;EACdC,MAAM;EACNC;AAC2B,CAAC,EAAE;EAC9B,MAAM;IAAEC,aAAa;IAAEC;EAAc,CAAC,GAAG,MAAM,IAAAC,qBAAc,GAAE;EAC/D;AACJ;AACA;EACI,MAAMC,oBAAoB,GAAG,IAAIC,4CAAoB,CAAC;IAClDC,IAAI,EAAEJ,aAAa;IACnBK,GAAG,EAAE,CAACN,aAAa;EACvB,CAAC,CAAC;EACF,MAAMO,qBAAqB,GAAG,MAAMb,qBAAqB,CAACc,IAAI,CAACL,oBAAoB,CAAC;EACpF;AACJ;AACA;EACI,IACI,OAAOI,qBAAqB,CAACE,gBAAgB,KAAK,QAAQ,IAC1DF,qBAAqB,CAACE,gBAAgB,KAAK,CAAC,EAC9C;IACEjB,OAAO,CAACkB,IAAI,CAAC,iCAAiC,CAAC;IAC/ClB,OAAO,CAACkB,IAAI,CAACH,qBAAqB,CAACI,aAAa,CAAC;EACrD;EACA;AACJ;AACA;EACI,MAAMC,iBAAiB,GAAG,IAAIC,yCAAiB,CAAC;IAC5CC,IAAI,EAAEb;EACV,CAAC,CAAC;EACF,MAAMP,qBAAqB,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
|
2
2
|
|
3
|
-
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
4
|
-
|
3
|
+
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
|
5
4
|
Object.defineProperty(exports, "__esModule", {
|
6
5
|
value: true
|
7
6
|
});
|
8
7
|
exports.shouldRestoreDatetime = exports.moveDateTimeToNextCentury = exports.moveDateTimeToCurrentCentury = exports.isDateTimeInNextCentury = exports.getIsoStringTillMinutes = exports.getApwSettings = exports.encodeToken = exports.documentClient = exports.decodeToken = exports.dateTimeToCronExpression = exports.basePlugins = exports.TOKEN_PREFIX = void 0;
|
9
|
-
|
10
8
|
var _dayjs = _interopRequireDefault(require("dayjs"));
|
11
|
-
|
12
9
|
var _utc = _interopRequireDefault(require("dayjs/plugin/utc"));
|
13
|
-
|
14
10
|
var _dynamodb = require("aws-sdk/clients/dynamodb");
|
15
|
-
|
16
11
|
var _handlerDb = _interopRequireDefault(require("@webiny/handler-db"));
|
17
|
-
|
18
12
|
var _dbDynamodb = require("@webiny/db-dynamodb");
|
19
|
-
|
20
13
|
var _plugins = _interopRequireDefault(require("@webiny/db-dynamodb/plugins"));
|
21
|
-
|
22
14
|
var _handlerLogs = _interopRequireDefault(require("@webiny/handler-logs"));
|
23
|
-
|
24
15
|
var _types = require("../types");
|
25
|
-
|
26
16
|
/**
|
27
17
|
* https://day.js.org/docs/en/plugin/utc
|
28
18
|
*/
|
29
19
|
_dayjs.default.extend(_utc.default);
|
30
|
-
|
31
20
|
const TIME_SEPARATOR = ":";
|
32
21
|
const ELAPSED_CRON_EXPRESSION = "* * * * ? 2000";
|
33
|
-
|
34
22
|
const getIsoStringTillMinutes = datetime => {
|
35
23
|
/**
|
36
24
|
* Validate datetime.
|
37
25
|
*/
|
38
26
|
if (isNaN(Date.parse(datetime))) {
|
39
27
|
return datetime;
|
40
|
-
}
|
28
|
+
}
|
29
|
+
// input = "2022-03-08T05:41:13.230Z"
|
41
30
|
// output = "2022-03-08T05:41"
|
42
|
-
|
43
|
-
|
44
31
|
return datetime.slice(0, datetime.lastIndexOf(TIME_SEPARATOR));
|
45
32
|
};
|
46
|
-
|
47
33
|
exports.getIsoStringTillMinutes = getIsoStringTillMinutes;
|
48
|
-
|
49
34
|
const dateTimeToCronExpression = datetime => {
|
50
35
|
if (!datetime) {
|
51
36
|
return ELAPSED_CRON_EXPRESSION;
|
@@ -56,32 +41,22 @@ const dateTimeToCronExpression = datetime => {
|
|
56
41
|
*
|
57
42
|
* https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html
|
58
43
|
*/
|
59
|
-
|
60
|
-
|
61
44
|
const dayOfWeek = "?";
|
62
45
|
return _dayjs.default.utc(datetime).format(`mm H D M [${dayOfWeek}] YYYY`);
|
63
46
|
};
|
64
|
-
|
65
47
|
exports.dateTimeToCronExpression = dateTimeToCronExpression;
|
66
|
-
|
67
48
|
const moveDateTimeToNextCentury = datetime => {
|
68
49
|
return _dayjs.default.utc(datetime).add(100, "year").toISOString();
|
69
50
|
};
|
70
|
-
|
71
51
|
exports.moveDateTimeToNextCentury = moveDateTimeToNextCentury;
|
72
|
-
|
73
52
|
const moveDateTimeToCurrentCentury = datetime => {
|
74
53
|
return _dayjs.default.utc(datetime).subtract(100, "year").toISOString();
|
75
54
|
};
|
76
|
-
|
77
55
|
exports.moveDateTimeToCurrentCentury = moveDateTimeToCurrentCentury;
|
78
|
-
|
79
56
|
const isDateTimeInNextCentury = datetime => {
|
80
57
|
return _dayjs.default.utc(datetime).isAfter("2100-01-01", "year");
|
81
58
|
};
|
82
|
-
|
83
59
|
exports.isDateTimeInNextCentury = isDateTimeInNextCentury;
|
84
|
-
|
85
60
|
const shouldRestoreDatetime = ({
|
86
61
|
invocationType,
|
87
62
|
datetime
|
@@ -93,16 +68,11 @@ const shouldRestoreDatetime = ({
|
|
93
68
|
* scheduled action if it has not been executed already.
|
94
69
|
*/
|
95
70
|
const selfInvoked = invocationType === _types.InvocationTypes.SCHEDULED;
|
96
|
-
|
97
71
|
const today = _dayjs.default.utc();
|
98
|
-
|
99
72
|
const isExecutionPending = _dayjs.default.utc(datetime).isAfter(today);
|
100
|
-
|
101
73
|
return !selfInvoked && isExecutionPending;
|
102
74
|
};
|
103
|
-
|
104
75
|
exports.shouldRestoreDatetime = shouldRestoreDatetime;
|
105
|
-
|
106
76
|
const encodeToken = ({
|
107
77
|
id,
|
108
78
|
tenant,
|
@@ -110,11 +80,9 @@ const encodeToken = ({
|
|
110
80
|
}) => {
|
111
81
|
return `${TOKEN_PREFIX}${id}__${tenant}__${locale}`;
|
112
82
|
};
|
113
|
-
|
114
83
|
exports.encodeToken = encodeToken;
|
115
84
|
const TOKEN_PREFIX = "apw-";
|
116
85
|
exports.TOKEN_PREFIX = TOKEN_PREFIX;
|
117
|
-
|
118
86
|
const decodeToken = token => {
|
119
87
|
const auth = token.slice(TOKEN_PREFIX.length);
|
120
88
|
const [id, tenant, locale] = auth.split("__");
|
@@ -124,27 +92,23 @@ const decodeToken = token => {
|
|
124
92
|
locale
|
125
93
|
};
|
126
94
|
};
|
127
|
-
|
128
95
|
exports.decodeToken = decodeToken;
|
129
96
|
const documentClient = new _dynamodb.DocumentClient({
|
130
97
|
convertEmptyValues: true,
|
131
98
|
region: process.env.AWS_REGION
|
132
99
|
});
|
133
100
|
exports.documentClient = documentClient;
|
134
|
-
|
135
101
|
const basePlugins = () => [(0, _plugins.default)(), (0, _handlerLogs.default)(), (0, _handlerDb.default)({
|
136
102
|
table: process.env.DB_TABLE,
|
137
103
|
driver: new _dbDynamodb.DynamoDbDriver({
|
138
104
|
documentClient
|
139
105
|
})
|
140
106
|
})];
|
107
|
+
|
141
108
|
/**
|
142
109
|
* Get APW settings record from DDB.
|
143
110
|
*/
|
144
|
-
|
145
|
-
|
146
111
|
exports.basePlugins = basePlugins;
|
147
|
-
|
148
112
|
const getApwSettings = async () => {
|
149
113
|
const variant = process.env.STAGED_ROLLOUTS_VARIANT;
|
150
114
|
const params = {
|
@@ -164,5 +128,4 @@ const getApwSettings = async () => {
|
|
164
128
|
eventTargetId: Item ? Item["eventTargetId"] : "eventTargetId"
|
165
129
|
};
|
166
130
|
};
|
167
|
-
|
168
131
|
exports.getApwSettings = getApwSettings;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"names":["dayjs","extend","utc","TIME_SEPARATOR","ELAPSED_CRON_EXPRESSION","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","cmsGraphqlFunctionArn","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 cmsGraphqlFunctionArn: 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 cmsGraphqlFunctionArn: Item ? Item[\"cmsGraphqlFunctionArn\"] : \"cmsGraphqlFunctionArn\",\n eventRuleName: Item ? Item[\"eventRuleName\"] : \"eventRuleName\",\n eventTargetId: Item ? Item[\"eventTargetId\"] : \"eventTargetId\"\n };\n};\n"],"mappings":"
|
1
|
+
{"version":3,"names":["dayjs","extend","utc","TIME_SEPARATOR","ELAPSED_CRON_EXPRESSION","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","cmsGraphqlFunctionArn","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 cmsGraphqlFunctionArn: 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 cmsGraphqlFunctionArn: Item ? Item[\"cmsGraphqlFunctionArn\"] : \"cmsGraphqlFunctionArn\",\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;AACAA,cAAK,CAACC,MAAM,CAACC,YAAG,CAAC;AAEjB,MAAMC,cAAc,GAAG,GAAG;AAC1B,MAAMC,uBAAuB,GAAG,gBAAgB;AAEzC,MAAMC,uBAAuB,GAAIC,QAAgB,IAAa;EACjE;AACJ;AACA;EACI,IAAIC,KAAK,CAACC,IAAI,CAACC,KAAK,CAACH,QAAQ,CAAC,CAAC,EAAE;IAC7B,OAAOA,QAAQ;EACnB;EACA;EACA;EACA,OAAOA,QAAQ,CAACI,KAAK,CAAC,CAAC,EAAEJ,QAAQ,CAACK,WAAW,CAACR,cAAc,CAAC,CAAC;AAClE,CAAC;AAAC;AAEK,MAAMS,wBAAwB,GAAIN,QAAgB,IAAa;EAClE,IAAI,CAACA,QAAQ,EAAE;IACX,OAAOF,uBAAuB;EAClC;EACA;AACJ;AACA;AACA;AACA;AACA;EACI,MAAMS,SAAS,GAAG,GAAG;EAErB,OAAOb,cAAK,CAACE,GAAG,CAACI,QAAQ,CAAC,CAACQ,MAAM,CAAE,aAAYD,SAAU,QAAO,CAAC;AACrE,CAAC;AAAC;AAEK,MAAME,yBAAyB,GAAIT,QAAgB,IAAa;EACnE,OAAON,cAAK,CAACE,GAAG,CAACI,QAAQ,CAAC,CAACU,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAACC,WAAW,EAAE;AAC7D,CAAC;AAAC;AAEK,MAAMC,4BAA4B,GAAIZ,QAAgB,IAAa;EACtE,OAAON,cAAK,CAACE,GAAG,CAACI,QAAQ,CAAC,CAACa,QAAQ,CAAC,GAAG,E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AMC,WAAW,GAAG,MAAM,CAC7B,IAAAC,gBAAe,GAAE,EACjB,IAAAC,oBAAW,GAAE,EACb,IAAAC,kBAAS,EAAC;EACNC,KAAK,EAAEP,OAAO,CAACC,GAAG,CAACO,QAAQ;EAC3BC,MAAM,EAAE,IAAIC,0BAAc,CAAC;IACvBd;EACJ,CAAC;AACL,CAAC,CAAC,CACL;;AAED;AACA;AACA;AAFA;AAUO,MAAMe,cAAc,GAAG,YAAkC;EAC5D,MAAMC,OAAO,GAAGZ,OAAO,CAACC,GAAG,CAACY,uBAAuB;EAEnD,MAAMC,MAAM,GAAG;IACXC,SAAS,EAAEf,OAAO,CAACC,GAAG,CAACO,QAAkB;IACzCQ,GAAG,EAAE;MACDC,EAAE,EAAG,cAAa;MAClBC,EAAE,EAAEN,OAAO,IAAI;IACnB;EACJ,CAAC;EAED,MAAM;IAAEO;EAAK,CAAC,GAAG,MAAMvB,cAAc,CAACwB,GAAG,CAACN,MAAM,CAAC,CAACO,OAAO,EAAE;EAE3D,OAAO;IACHC,sBAAsB,EAAEH,IAAI,GAAGA,IAAI,CAAC,wBAAwB,CAAC,GAAG,wBAAwB;IACxFI,qBAAqB,EAAEJ,IAAI,GAAGA,IAAI,CAAC,uBAAuB,CAAC,GAAG,uBAAuB;IACrFK,aAAa,EAAEL,IAAI,GAAGA,IAAI,CAAC,eAAe,CAAC,GAAG,eAAe;IAC7DM,aAAa,EAAEN,IAAI,GAAGA,IAAI,CAAC,eAAe,CAAC,GAAG;EAClD,CAAC;AACL,CAAC;AAAC"}
|
package/scheduler/index.js
CHANGED
@@ -4,9 +4,7 @@ Object.defineProperty(exports, "__esModule", {
|
|
4
4
|
value: true
|
5
5
|
});
|
6
6
|
exports.createScheduler = void 0;
|
7
|
-
|
8
7
|
var _createScheduleActionMethods = require("./createScheduleActionMethods");
|
9
|
-
|
10
8
|
const createScheduler = params => {
|
11
9
|
const {
|
12
10
|
getLocale,
|
@@ -23,5 +21,4 @@ const createScheduler = params => {
|
|
23
21
|
storageOperations
|
24
22
|
});
|
25
23
|
};
|
26
|
-
|
27
24
|
exports.createScheduler = createScheduler;
|
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":"
|
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,MAAMA,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;AAAC"}
|