@webiny/api-apw 5.34.6-beta.4 → 5.34.6-beta.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webiny/api-apw",
3
- "version": "5.34.6-beta.4",
3
+ "version": "5.34.6-beta.6",
4
4
  "keywords": [
5
5
  "apw:base"
6
6
  ],
@@ -17,27 +17,27 @@
17
17
  "@aws-sdk/client-cloudwatch-events": "3.186.0",
18
18
  "@babel/runtime": "7.19.0",
19
19
  "@commodo/fields": "1.1.2-beta.20",
20
- "@webiny/api": "5.34.6-beta.4",
21
- "@webiny/api-admin-settings": "5.34.6-beta.4",
22
- "@webiny/api-headless-cms": "5.34.6-beta.4",
23
- "@webiny/api-i18n": "5.34.6-beta.4",
24
- "@webiny/api-i18n-ddb": "5.34.6-beta.4",
25
- "@webiny/api-mailer": "5.34.6-beta.4",
26
- "@webiny/api-page-builder": "5.34.6-beta.4",
27
- "@webiny/api-security": "5.34.6-beta.4",
28
- "@webiny/api-tenancy": "5.34.6-beta.4",
29
- "@webiny/api-wcp": "5.34.6-beta.4",
30
- "@webiny/db-dynamodb": "5.34.6-beta.4",
31
- "@webiny/error": "5.34.6-beta.4",
32
- "@webiny/handler": "5.34.6-beta.4",
33
- "@webiny/handler-client": "5.34.6-beta.4",
34
- "@webiny/handler-db": "5.34.6-beta.4",
35
- "@webiny/handler-graphql": "5.34.6-beta.4",
36
- "@webiny/handler-logs": "5.34.6-beta.4",
37
- "@webiny/plugins": "5.34.6-beta.4",
38
- "@webiny/pubsub": "5.34.6-beta.4",
39
- "@webiny/utils": "5.34.6-beta.4",
40
- "@webiny/validation": "5.34.6-beta.4",
20
+ "@webiny/api": "5.34.6-beta.6",
21
+ "@webiny/api-admin-settings": "5.34.6-beta.6",
22
+ "@webiny/api-headless-cms": "5.34.6-beta.6",
23
+ "@webiny/api-i18n": "5.34.6-beta.6",
24
+ "@webiny/api-i18n-ddb": "5.34.6-beta.6",
25
+ "@webiny/api-mailer": "5.34.6-beta.6",
26
+ "@webiny/api-page-builder": "5.34.6-beta.6",
27
+ "@webiny/api-security": "5.34.6-beta.6",
28
+ "@webiny/api-tenancy": "5.34.6-beta.6",
29
+ "@webiny/api-wcp": "5.34.6-beta.6",
30
+ "@webiny/db-dynamodb": "5.34.6-beta.6",
31
+ "@webiny/error": "5.34.6-beta.6",
32
+ "@webiny/handler": "5.34.6-beta.6",
33
+ "@webiny/handler-client": "5.34.6-beta.6",
34
+ "@webiny/handler-db": "5.34.6-beta.6",
35
+ "@webiny/handler-graphql": "5.34.6-beta.6",
36
+ "@webiny/handler-logs": "5.34.6-beta.6",
37
+ "@webiny/plugins": "5.34.6-beta.6",
38
+ "@webiny/pubsub": "5.34.6-beta.6",
39
+ "@webiny/utils": "5.34.6-beta.6",
40
+ "@webiny/validation": "5.34.6-beta.6",
41
41
  "dayjs": "1.11.5",
42
42
  "lodash": "4.17.21",
43
43
  "mdbid": "1.0.0"
@@ -46,14 +46,14 @@
46
46
  "@babel/cli": "^7.19.3",
47
47
  "@babel/core": "^7.19.3",
48
48
  "@babel/preset-env": "^7.19.4",
49
- "@webiny/api-headless-cms-ddb": "^5.34.6-beta.4",
50
- "@webiny/api-page-builder-so-ddb": "^5.34.6-beta.4",
51
- "@webiny/api-security-so-ddb": "^5.34.6-beta.4",
52
- "@webiny/api-tenancy-so-ddb": "^5.34.6-beta.4",
53
- "@webiny/cli": "^5.34.6-beta.4",
54
- "@webiny/handler-aws": "^5.34.6-beta.4",
55
- "@webiny/project-utils": "^5.34.6-beta.4",
56
- "@webiny/wcp": "^5.34.6-beta.4",
49
+ "@webiny/api-headless-cms-ddb": "^5.34.6-beta.6",
50
+ "@webiny/api-page-builder-so-ddb": "^5.34.6-beta.6",
51
+ "@webiny/api-security-so-ddb": "^5.34.6-beta.6",
52
+ "@webiny/api-tenancy-so-ddb": "^5.34.6-beta.6",
53
+ "@webiny/cli": "^5.34.6-beta.6",
54
+ "@webiny/handler-aws": "^5.34.6-beta.6",
55
+ "@webiny/project-utils": "^5.34.6-beta.6",
56
+ "@webiny/wcp": "^5.34.6-beta.6",
57
57
  "get-yarn-workspaces": "^1.0.2",
58
58
  "graphql": "^15.7.2",
59
59
  "jest": "^28.1.0",
@@ -72,5 +72,5 @@
72
72
  "build": "yarn webiny run build",
73
73
  "watch": "yarn webiny run watch"
74
74
  },
75
- "gitHead": "db8834165f3dee74849d4bf077a29b26d899d0de"
75
+ "gitHead": "b4142ace8452d98c7773e846b0b1fb8164ea80c6"
76
76
  }
@@ -9,5 +9,5 @@ export interface HandlerArgs {
9
9
  interface Configuration {
10
10
  storageOperations: ApwScheduleActionStorageOperations;
11
11
  }
12
- export declare const executeActionHandlerPlugins: (config: Configuration) => ((import("@webiny/handler").HandlerResultPlugin<import("@webiny/handler/types").Context> | import("@webiny/db-dynamodb/plugins/definitions/ValueFilterPlugin").ValueFilterPlugin[][] | ContextPlugin<import("@webiny/handler-db/types").DbContext>[])[] | import("@webiny/handler").EventPlugin<HandlerArgs, import("@webiny/handler/types").Context, any> | ContextPlugin<import("@webiny/api/types").Context>)[];
12
+ export declare const executeActionHandlerPlugins: (config: Configuration) => ((import("@webiny/handler").HandlerResultPlugin<import("@webiny/handler/types").Context> | import("@webiny/db-dynamodb/plugins/definitions/ValueFilterPlugin").ValueFilterPlugin[][] | ContextPlugin<import("@webiny/handler-db/types").DbContext>[])[] | import("@webiny/handler-aws").RawEventHandler<HandlerArgs, import("@webiny/handler/types").Context, any> | ContextPlugin<import("@webiny/api/types").Context>)[];
13
13
  export {};
@@ -15,7 +15,7 @@ var _HeadlessCMSGraphQL = require("./plugins/HeadlessCMSGraphQL");
15
15
 
16
16
  var _ApplicationGraphQL = require("./plugins/ApplicationGraphQL");
17
17
 
18
- var _handler = require("@webiny/handler");
18
+ var _handlerAws = require("@webiny/handler-aws");
19
19
 
20
20
  /**
21
21
  * Handler that execute the provided action(s) for the schedule action workflow.
@@ -24,7 +24,7 @@ const createExecuteActionLambda = params => {
24
24
  const {
25
25
  storageOperations
26
26
  } = params;
27
- return (0, _handler.createEvent)(async ({
27
+ return (0, _handlerAws.createRawEventHandler)(async ({
28
28
  payload,
29
29
  context
30
30
  }) => {
@@ -136,8 +136,9 @@ const createExecuteActionLambda = params => {
136
136
  console.error(`There is no GraphQL body defined, in the Plugin, for type "${item.data.type}".`);
137
137
  console.log(JSON.stringify(item));
138
138
  continue;
139
- } // Perform the actual action call.
139
+ }
140
140
 
141
+ console.log(`Invoking Lambda "${name}" with url "${url}".`); // Perform the actual action call.
141
142
 
142
143
  const response = await context.handlerClient.invoke({
143
144
  name,
@@ -158,10 +159,31 @@ const createExecuteActionLambda = params => {
158
159
  },
159
160
  await: true
160
161
  });
162
+ /**
163
+ *
164
+ */
165
+
166
+ await storageOperations.delete({
167
+ locale,
168
+ tenant,
169
+ id: item.id
170
+ });
171
+ /**
172
+ * Check for the response and log the error if any.
173
+ */
161
174
 
162
175
  if (response !== null && response !== void 0 && response.body) {
176
+ var _response$body$data, _response$body$data$c;
177
+
178
+ const error = (_response$body$data = response.body.data) === null || _response$body$data === void 0 ? void 0 : (_response$body$data$c = _response$body$data.content) === null || _response$body$data$c === void 0 ? void 0 : _response$body$data$c.error;
179
+
180
+ if (!error) {
181
+ console.log("Invoke successful.");
182
+ continue;
183
+ }
184
+
163
185
  console.log(JSON.stringify({
164
- body: response.body
186
+ error
165
187
  }, null, 2));
166
188
  continue;
167
189
  }
@@ -1 +1 @@
1
- {"version":3,"names":["createExecuteActionLambda","params","storageOperations","createEvent","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","e","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 { createEvent } from \"@webiny/handler\";\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 createEvent<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 // 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 if (response?.body) {\n console.log(JSON.stringify({ body: response.body }, 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 (e) {\n log(\"[HANDLER_EXECUTE_ACTION] Error => \", e);\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,MAAD,IAA2B;EACzD,MAAM;IAAEC;EAAF,IAAwBD,MAA9B;EAEA,OAAO,IAAAE,oBAAA,EAAyB,OAAO;IAAEC,OAAF;IAAWC;EAAX,CAAP,KAAgC;IAC5D,MAAMC,GAAG,GAAGC,OAAO,CAACD,GAApB;IAEA,MAAME,yBAAyB,GAAGH,OAAO,CAACI,OAAR,CAAgBC,MAAhB,CAC9BC,sCAAA,CAAmBC,IADW,CAAlC;;IAIA,IAAIJ,yBAAyB,CAACK,MAA1B,KAAqC,CAAzC,EAA4C;MACxCN,OAAO,CAACO,KAAR,CAAe,mEAAf;MACA;IACH;;IAED,MAAMC,6BAAiE,GAAG,EAA1E;;IAEA,MAAMC,2BAA2B,GAC7BC,IADgC,IAEJ;MAC5B,MAAM;QAAEL;MAAF,IAAWK,IAAjB;;MACA,IAAIF,6BAA6B,CAACH,IAAD,CAAjC,EAAyC;QACrC,OAAOG,6BAA6B,CAACH,IAAD,CAApC;MACH;;MACD,KAAK,MAAMM,MAAX,IAAqBV,yBAArB,EAAgD;QAC5C,IAAI,CAACU,MAAM,CAACC,MAAP,CAAcF,IAAd,CAAL,EAA0B;UACtB;QACH;;QACDF,6BAA6B,CAACH,IAAD,CAA7B,GAAsCM,MAAtC;QACA,OAAOA,MAAP;MACH;;MACD,OAAO,IAAP;IACH,CAfD;;IAiBA,IAAI;MACA,MAAME,WAAW,GAAG,MAAM,IAAAC,qBAAA,GAA1B;MAEA,MAAM;QAAEC,cAAc,EAAEC,QAAlB;QAA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AAL,CAAeM,IAAf;UAbD,CAFuC;UAiBhDW,KAAK,EAAE;QAjByC,CAA7B,CAAvB;;QAmBA,IAAIT,QAAJ,aAAIA,QAAJ,eAAIA,QAAQ,CAAEF,IAAd,EAAoB;UAChBnC,OAAO,CAACD,GAAR,CAAY6B,IAAI,CAACC,SAAL,CAAe;YAAEM,IAAI,EAAEE,QAAQ,CAACF;UAAjB,CAAf,EAAwC,IAAxC,EAA8C,CAA9C,CAAZ;UACA;QACH;;QACDnC,OAAO,CAACD,GAAR,CAAY6B,IAAI,CAACC,SAAL,CAAe;UAAEQ;QAAF,CAAf,EAA6B,IAA7B,EAAmC,CAAnC,CAAZ,EAxEsB,CA0EtB;MACH;IACJ,CA5GD,CA4GE,OAAOU,CAAP,EAAU;MACRhD,GAAG,CAAC,oCAAD,EAAuCgD,CAAvC,CAAH,CADQ,CAER;IACH;EACJ,CA/IM,CAAP;AAgJH,CAnJD;;AAqJO,MAAMC,2BAA2B,GAAIC,MAAD,IAA2B,CAClE,IAAIC,kBAAJ,CAAkB,MAAMpD,OAAN,IAAiB;EAC/BA,OAAO,CAACI,OAAR,CAAgBiD,QAAhB,CAAyB,CAAC,IAAIC,sCAAJ,EAAD,EAA2B,IAAIC,sCAAJ,EAA3B,CAAzB;AACH,CAFD,CADkE,EAIlE,IAAAC,kBAAA,GAJkE,EAKlE7D,yBAAyB,CAACwD,MAAD,CALyC,CAA/D"}
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","e","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 (e) {\n log(\"[HANDLER_EXECUTE_ACTION] Error => \", e);\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,MAAD,IAA2B;EACzD,MAAM;IAAEC;EAAF,IAAwBD,MAA9B;EAEA,OAAO,IAAAE,iCAAA,EAAmC,OAAO;IAAEC,OAAF;IAAWC;EAAX,CAAP,KAAgC;IACtE,MAAMC,GAAG,GAAGC,OAAO,CAACD,GAApB;IAEA,MAAME,yBAAyB,GAAGH,OAAO,CAACI,OAAR,CAAgBC,MAAhB,CAC9BC,sCAAA,CAAmBC,IADW,CAAlC;;IAIA,IAAIJ,yBAAyB,CAACK,MAA1B,KAAqC,CAAzC,EAA4C;MACxCN,OAAO,CAACO,KAAR,CAAe,mEAAf;MACA;IACH;;IAED,MAAMC,6BAAiE,GAAG,EAA1E;;IAEA,MAAMC,2BAA2B,GAC7BC,IADgC,IAEJ;MAC5B,MAAM;QAAEL;MAAF,IAAWK,IAAjB;;MACA,IAAIF,6BAA6B,CAACH,IAAD,CAAjC,EAAyC;QACrC,OAAOG,6BAA6B,CAACH,IAAD,CAApC;MACH;;MACD,KAAK,MAAMM,MAAX,IAAqBV,yBAArB,EAAgD;QAC5C,IAAI,CAACU,MAAM,CAACC,MAAP,CAAcF,IAAd,CAAL,EAA0B;UACtB;QACH;;QACDF,6BAA6B,CAACH,IAAD,CAA7B,GAAsCM,MAAtC;QACA,OAAOA,MAAP;MACH;;MAC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AAR,CAAgBmD,QAAhB,CAAyB,CAAC,IAAIC,sCAAJ,EAAD,EAA2B,IAAIC,sCAAJ,EAA3B,CAAzB;AACH,CAFD,CADkE,EAIlE,IAAAC,kBAAA,GAJkE,EAKlE/D,yBAAyB,CAAC0D,MAAD,CALyC,CAA/D"}
@@ -153,6 +153,8 @@ const executeTask = async ({
153
153
  },
154
154
  await: false
155
155
  });
156
+ } else {
157
+ console.log(`context.handlerClient.invoke is not a function!`);
156
158
  }
157
159
  /**
158
160
  * Delete current schedule Task. So that, we can schedule a new one later.
@@ -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":";;;;;;;;;;;;;AAAA;;AAEA;;AAKA;;AASA,MAAMA,GAAG,GAAGC,OAAO,CAACD,GAApB;;AAOA;AACA;AACA;AACA;AACA;AACO,eAAeE,uBAAf,CAAuC;EAC1CC,qBAD0C;EAE1CC,kBAF0C;EAG1CC,QAH0C;EA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BC,aAH8B;EAI9Bb;AAJ8B,CAAP,KAKa;EACpC/C,GAAG,CAAE,qBAAF,EAAwB,IAAI6D,IAAJ,GAAWC,WAAX,EAAxB,CAAH;;EAEA,IAAI,OAAOF,aAAa,CAACG,MAArB,KAAgC,UAApC,EAAgD;IAC5C,MAAMH,aAAa,CAACG,MAAd,CAAqB;MACvBC,IAAI,EAAEL,UADiB;MAEvBM,OAAO,EAAE;QACL3D,cAAc,EAAEoD,IAAI,CAACpD,cADhB;QAELD,QAAQ,EAAEqD,IAAI,CAACrD,QAFV;QAGLE,MAAM,EAAEmD,IAAI,CAACnD,MAHR;QAILC,MAAM,EAAEkD,IAAI,CAAClD;MAJR,CAFc;MAQvB0D,KAAK,EAAE;IARgB,CAArB,CAAN;EAUH;EAED;AACJ;AACA;;;EACI,IAAI;IACA,MAAMnB,iBAAiB,CAACoB,iBAAlB,CAAoC;MACtC5D,MAAM,EAAEmD,IAAI,CAACnD,MADyB;MAEtCC,MAAM,EAAEkD,IAAI,CAAClD;IAFyB,CAApC,CAAN;EAIH,CALD,CAKE,OAAO4D,CAAP,EAAU;IACRnE,OAAO,CAACoE,KAAR,CAAcD,CAAd;EACH;AACJ,CAhCM"}
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,MAAMA,GAAG,GAAGC,OAAO,CAACD,GAApB;;AAOA;AACA;AACA;AACA;AACA;AACO,eAAeE,uBAAf,CAAuC;EAC1CC,qBAD0C;EAE1CC,kBAF0C;EAG1CC,QAH0C;EAI1CC,cAJ0C;EAK1CC,MAL0C;EAM1CC;AAN0C,CAAvC,EAO2B;EAC9B,MAAM;IAAEC,aAAF;IAAiBC;EAAjB,IAAmC,MAAM,IAAAC,qBAAA,GAA/C;EACA;AACJ;AACA;;EACI,MAAMC,oBAAoB,GAAG,IAAIC,4CAAJ,CAAyB;IAClDC,IAAI,EAAEJ,aAD4C;IAElDK,GAAG,EAAE,CAACN,aAAD;EAF6C,CAAzB,CAA7B;EAIA,MAAMO,qBAAqB,GAAG,MAAMb,qBAAqB,CAACc,IAAtB,CAA2BL,oBAA3B,CAApC;EACA;AACJ;AACA;;EACI,IACI,OAAOI,qBAAqB,CAACE,gBAA7B,KAAkD,QAAlD,IACAF,qBAAqB,CAACE,gBAAtB,KAA2C,CAF/C,EAGE;IACEjB,OAAO,CAACkB,IAAR,CAAa,iCAAb;IACAlB,OAAO,CAACkB,IAAR,CAAaH,qBAAqB,CAACI,aAAnC;EACH;EACD;AACJ;AACA;;;EACI,MAAMC,iBAAiB,GAAG,IAAIC,yCAAJ,CAAsB;IAC5CC,IAAI,EAAEb;EADsC,CAAtB,CAA1B;EAGA,MAAMP,qBAAqB,CAACc,IAAtB,CAA2BI,iBAA3B,CAAN;EAEA;AACJ;AACA;AACA;AACA;;EACI,MAAMG,cAAc,GAAG,IAA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