From 41c1809891ee0fceb78ab141619494b5c780bee4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 3 Aug 2023 16:48:55 +0000 Subject: [PATCH 01/45] Bump wrangler from 3.0.0 to 3.1.1 Bumps [wrangler](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler) from 3.0.0 to 3.1.1. - [Release notes](https://github.com/cloudflare/workers-sdk/releases) - [Changelog](https://github.com/cloudflare/workers-sdk/blob/main/packages/wrangler/CHANGELOG.md) - [Commits](https://github.com/cloudflare/workers-sdk/commits/wrangler@3.1.1/packages/wrangler) --- updated-dependencies: - dependency-name: wrangler dependency-type: direct:development ... Signed-off-by: dependabot[bot] --- package-lock.json | 10 +++++----- package.json | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 5a00182..d2e98bc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -24,7 +24,7 @@ "ts-jest": "29.1.1", "ts-node": "10.9.1", "typescript": "5.1.6", - "wrangler": "3.0.0" + "wrangler": "3.1.1" } }, "node_modules/@aashutoshrathi/word-wrap": { @@ -6263,9 +6263,9 @@ } }, "node_modules/wrangler": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-3.0.0.tgz", - "integrity": "sha512-azppXJjEQeaVg3wxFZJOGDGtpR8e9clHr2aHuanGHOk9vX3gvesCv97BF/n8qh1Y1d7vDKOBdfQW3UOYZNFGNw==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-3.1.1.tgz", + "integrity": "sha512-iG6QGOt+qgSm7UroJ8IJ+JdXEcDcW7yp9ilP0V7alCGhKm8shqa/M1iyMOpukZSCSZo8Vmn5nH2C9OY1PR3dQQ==", "dev": true, "dependencies": { "@cloudflare/kv-asset-handler": "^0.2.0", @@ -6274,7 +6274,7 @@ "blake3-wasm": "^2.1.5", "chokidar": "^3.5.3", "esbuild": "0.16.3", - "miniflare": "^3.0.0", + "miniflare": "^3.0.1", "nanoid": "^3.3.3", "path-to-regexp": "^6.2.0", "selfsigned": "^2.0.1", diff --git a/package.json b/package.json index 492e1a6..452b70b 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ "ts-jest": "29.1.1", "ts-node": "10.9.1", "typescript": "5.1.6", - "wrangler": "3.0.0" + "wrangler": "3.1.1" }, "dependencies": { "@tsndr/cloudflare-worker-jwt": "2.2.1" From 0151087f320c1897ae9cc8c215ae068550890e26 Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Fri, 22 Sep 2023 19:01:04 +0530 Subject: [PATCH 02/45] feat: OOO Nickname Update Job --- src/config/config.ts | 2 +- src/constants.ts | 4 +++ src/handlers/scheduledEventHandler.ts | 46 +++++++++++++++++++++++++++ src/worker.ts | 13 ++++++-- wrangler.toml | 18 +++++++---- 5 files changed, 74 insertions(+), 9 deletions(-) create mode 100644 src/constants.ts diff --git a/src/config/config.ts b/src/config/config.ts index 48446f4..f1d7c10 100644 --- a/src/config/config.ts +++ b/src/config/config.ts @@ -9,7 +9,7 @@ export const handleConfig = (env: env) => { baseUrl = 'https://staging-api.realdevsquad.com'; } } else { - baseUrl = 'https://staging-api.realdevsquad.com'; + baseUrl = 'https://93f5-49-204-135-151.ngrok.io'; } return { baseUrl }; }; diff --git a/src/constants.ts b/src/constants.ts new file mode 100644 index 0000000..3b231ab --- /dev/null +++ b/src/constants.ts @@ -0,0 +1,4 @@ +const KEY_NAME = 'DISCORD_NICKNAME_CHANGED'; +const NAMESPACE_NAME = 'CRON_JOBS_TIMESTAMPS'; + +export { KEY_NAME, NAMESPACE_NAME }; diff --git a/src/handlers/scheduledEventHandler.ts b/src/handlers/scheduledEventHandler.ts index 290112e..1b83916 100644 --- a/src/handlers/scheduledEventHandler.ts +++ b/src/handlers/scheduledEventHandler.ts @@ -1,8 +1,54 @@ +import { KVNamespace } from '@cloudflare/workers-types'; + import { handleConfig } from '../config/config'; +import { KEY_NAME, NAMESPACE_NAME } from '../constants'; import { env } from '../types/global.types'; +import { generateJwt } from '../utils/generateJwt'; export async function ping(env: env) { const url = handleConfig(env); const response = await fetch(`${url.baseUrl}/healthcheck`); return response; } + +export async function callDiscordNicknameBatchUpdate(env: env) { + const namespace = env[NAMESPACE_NAME] as unknown as KVNamespace; + let lastNicknameUpdate: string | number = 0; + try { + lastNicknameUpdate = (await namespace.get(KEY_NAME)) ?? 0; + } catch (err) { + console.log('Error while fetching the timestamp for last nickname update'); + throw err; + } + + const url = handleConfig(env); + let token; + try { + token = await generateJwt(env); + } catch (err) { + console.log(`Error while generating JWT token: ${err}`); + throw err; + } + const response = await fetch(`${url.baseUrl}/discord-actions/nickname/status`, { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + lastNicknameUpdate, + }), + }); + if (!response.ok) { + throw new Error("Error while trying to update users' discord nickname"); + } + + try { + await namespace.put(KEY_NAME, Date.now().toString()); + } catch (err) { + console.log('Error while trying to update the last nickname change timestamp'); + } + + const data = await response.json(); + return data; +} diff --git a/src/worker.ts b/src/worker.ts index e90e029..e80ef1a 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -1,4 +1,4 @@ -import { ping } from './handlers/scheduledEventHandler'; +import { callDiscordNicknameBatchUpdate, ping } from './handlers/scheduledEventHandler'; import { env } from './types/global.types'; export default { @@ -6,7 +6,16 @@ export default { // for more details read here: https://community.cloudflare.com/t/waituntil-is-not-a-function-when-using-workers-with-modules/375781/4 // eslint-disable-next-line no-unused-vars async scheduled(req: Request, env: env, ctx: ExecutionContext) { - ctx.waitUntil(ping(env)); + switch (req.cron) { + case '0 */4 * * *': + ctx.waitUntil(ping(env)); + break; + case '0 */6 * * *': + await callDiscordNicknameBatchUpdate(env); + break; + default: + console.log('Unknown Trigger Value!'); + } }, // We need to keep all 3 parameters in this format even if they are not used as as cloudflare workers need them to be present So we are disabling eslint rule of no-unused-vars // for more details read here: https://community.cloudflare.com/t/waituntil-is-not-a-function-when-using-workers-with-modules/375781/4 diff --git a/wrangler.toml b/wrangler.toml index c6455e0..0d6c916 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -1,13 +1,19 @@ name = "cron-jobs" main = "src/worker.ts" compatibility_date = "2023-07-17" -[triggers] -crons = ["0 */4 * * *"] -# # KV Namespace binding - For more information: https://developers.cloudflare.com/workers/runtime-apis/kv -# [[kv_namespaces]] -# binding = "MY_KV_NAMESPACE" -# id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +kv_namespaces = [ + { binding = "CRON_JOBS_TIMESTAMPS", id = "a5431887e6c94dc9b3e36c35a07081b9" } +] + +# [env.production] +# the BINDING_NAME must be CRON_JOBS_TIMESTAMPS to override in the production env +# kv_namespaces = [ +# { binding = "", id = "" } +# ] + +[triggers] +crons = ["0 */4 * * *", "0 */6 * * *"] # # Durable Object binding - For more information: https://developers.cloudflare.com/workers/runtime-apis/durable-objects # [[durable_objects]] From 21ee1df1e12d07cddc5e401fda8ad46bb8fc2054 Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Sat, 30 Sep 2023 19:31:15 +0530 Subject: [PATCH 03/45] refactor: baseUrl to staging API URL --- src/config/config.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/config.ts b/src/config/config.ts index f1d7c10..48446f4 100644 --- a/src/config/config.ts +++ b/src/config/config.ts @@ -9,7 +9,7 @@ export const handleConfig = (env: env) => { baseUrl = 'https://staging-api.realdevsquad.com'; } } else { - baseUrl = 'https://93f5-49-204-135-151.ngrok.io'; + baseUrl = 'https://staging-api.realdevsquad.com'; } return { baseUrl }; }; From f1f132d9b59299bdd4733974a98ad256526f3430 Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Sat, 30 Sep 2023 21:17:13 +0530 Subject: [PATCH 04/45] refactor: namespace key name --- src/constants.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/constants.ts b/src/constants.ts index 3b231ab..f682c83 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -1,4 +1,4 @@ -const KEY_NAME = 'DISCORD_NICKNAME_CHANGED'; +const DISCORD_NICKNAME_CHANGED_TIMESTAMP = 'DISCORD_NICKNAME_CHANGED'; const NAMESPACE_NAME = 'CRON_JOBS_TIMESTAMPS'; -export { KEY_NAME, NAMESPACE_NAME }; +export { DISCORD_NICKNAME_CHANGED_TIMESTAMP, NAMESPACE_NAME }; From fec88f7feb4964ed865b5ae77260657c2ee67cbd Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Sun, 1 Oct 2023 07:32:39 +0530 Subject: [PATCH 05/45] feat: nickname batch update response type --- src/types/global.types.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/types/global.types.ts b/src/types/global.types.ts index 89578cd..19cbd3f 100644 --- a/src/types/global.types.ts +++ b/src/types/global.types.ts @@ -1,3 +1,12 @@ export type env = { [key: string]: string; }; + +export type nicknameUpdateResponseType = { + message: string; + data: { + totalUsersStatus: number; + successfulNicknameUpdates: number; + unsuccessfulNicknameUpdates: number; + }; +}; From 47859dea19086cde4984fb5195e0952b2886704e Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Sun, 1 Oct 2023 07:34:43 +0530 Subject: [PATCH 06/45] refactor: scheduled handler type, return response --- src/worker.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/worker.ts b/src/worker.ts index e80ef1a..08040a2 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -5,14 +5,13 @@ export default { // We need to keep all 3 parameters in this format even if they are not used as as cloudflare workers need them to be present So we are disabling eslint rule of no-unused-vars // for more details read here: https://community.cloudflare.com/t/waituntil-is-not-a-function-when-using-workers-with-modules/375781/4 // eslint-disable-next-line no-unused-vars - async scheduled(req: Request, env: env, ctx: ExecutionContext) { + async scheduled(req: ScheduledController, env: env, ctx: ExecutionContext) { switch (req.cron) { case '0 */4 * * *': ctx.waitUntil(ping(env)); break; case '0 */6 * * *': - await callDiscordNicknameBatchUpdate(env); - break; + return await callDiscordNicknameBatchUpdate(env); default: console.log('Unknown Trigger Value!'); } From 7b0bf9187bc8d3e046034e9e38f58463901317a7 Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Sun, 1 Oct 2023 07:36:36 +0530 Subject: [PATCH 07/45] refactor: key constant, return data --- src/handlers/scheduledEventHandler.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/handlers/scheduledEventHandler.ts b/src/handlers/scheduledEventHandler.ts index 1b83916..c225774 100644 --- a/src/handlers/scheduledEventHandler.ts +++ b/src/handlers/scheduledEventHandler.ts @@ -1,8 +1,8 @@ import { KVNamespace } from '@cloudflare/workers-types'; import { handleConfig } from '../config/config'; -import { KEY_NAME, NAMESPACE_NAME } from '../constants'; -import { env } from '../types/global.types'; +import { DISCORD_NICKNAME_CHANGED_TIMESTAMP, NAMESPACE_NAME } from '../constants'; +import { env, nicknameUpdateResponseType } from '../types/global.types'; import { generateJwt } from '../utils/generateJwt'; export async function ping(env: env) { @@ -15,7 +15,7 @@ export async function callDiscordNicknameBatchUpdate(env: env) { const namespace = env[NAMESPACE_NAME] as unknown as KVNamespace; let lastNicknameUpdate: string | number = 0; try { - lastNicknameUpdate = (await namespace.get(KEY_NAME)) ?? 0; + lastNicknameUpdate = (await namespace.get(DISCORD_NICKNAME_CHANGED_TIMESTAMP)) ?? 0; } catch (err) { console.log('Error while fetching the timestamp for last nickname update'); throw err; @@ -43,12 +43,15 @@ export async function callDiscordNicknameBatchUpdate(env: env) { throw new Error("Error while trying to update users' discord nickname"); } + const data: nicknameUpdateResponseType = await response.json(); + if (data?.data.totalUsersStatus !== 0 && data?.data.successfulNicknameUpdates === 0) { + throw new Error("Error while trying to update users' discord nickname"); + } try { - await namespace.put(KEY_NAME, Date.now().toString()); + await namespace.put(DISCORD_NICKNAME_CHANGED_TIMESTAMP, Date.now().toString()); } catch (err) { console.log('Error while trying to update the last nickname change timestamp'); } - const data = await response.json(); return data; } From 2a012f1f496c35ac05104a26eeb50fb9cc664f2f Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Sun, 1 Oct 2023 13:47:57 +0530 Subject: [PATCH 08/45] refactor: production and staging kv namespace template --- wrangler.toml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/wrangler.toml b/wrangler.toml index 0d6c916..6dbc0e9 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -6,6 +6,12 @@ kv_namespaces = [ { binding = "CRON_JOBS_TIMESTAMPS", id = "a5431887e6c94dc9b3e36c35a07081b9" } ] +# [env.staging] +# the BINDING_NAME must be CRON_JOBS_TIMESTAMPS to override in the staging env +# kv_namespaces = [ +# { binding = "", id = "" } +# ] + # [env.production] # the BINDING_NAME must be CRON_JOBS_TIMESTAMPS to override in the production env # kv_namespaces = [ From 40a854bd4fa37c6f37e79caeb24bb659d5f839c0 Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Sun, 1 Oct 2023 23:00:51 +0530 Subject: [PATCH 09/45] refactor: throw err for null KV namespace --- src/handlers/scheduledEventHandler.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/handlers/scheduledEventHandler.ts b/src/handlers/scheduledEventHandler.ts index c225774..88dd2d0 100644 --- a/src/handlers/scheduledEventHandler.ts +++ b/src/handlers/scheduledEventHandler.ts @@ -13,9 +13,12 @@ export async function ping(env: env) { export async function callDiscordNicknameBatchUpdate(env: env) { const namespace = env[NAMESPACE_NAME] as unknown as KVNamespace; - let lastNicknameUpdate: string | number = 0; + let lastNicknameUpdate: string | number | null = 0; try { - lastNicknameUpdate = (await namespace.get(DISCORD_NICKNAME_CHANGED_TIMESTAMP)) ?? 0; + lastNicknameUpdate = await namespace.get(DISCORD_NICKNAME_CHANGED_TIMESTAMP); + if (lastNicknameUpdate === null) { + throw new Error('Error while fetching KV "DISCORD_NICKNAME_CHANGED_TIMESTAMP"'); + } } catch (err) { console.log('Error while fetching the timestamp for last nickname update'); throw err; From 2ddb96beeafaf918e532c05bcf17a466c2d3d9e2 Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Sat, 7 Oct 2023 19:43:13 +0530 Subject: [PATCH 10/45] refactor: remove DISCORD_NICKNAME_CHANGED constant --- src/constants.ts | 3 +-- src/handlers/scheduledEventHandler.ts | 8 ++++---- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/constants.ts b/src/constants.ts index f682c83..c87b29d 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -1,4 +1,3 @@ -const DISCORD_NICKNAME_CHANGED_TIMESTAMP = 'DISCORD_NICKNAME_CHANGED'; const NAMESPACE_NAME = 'CRON_JOBS_TIMESTAMPS'; -export { DISCORD_NICKNAME_CHANGED_TIMESTAMP, NAMESPACE_NAME }; +export { NAMESPACE_NAME }; diff --git a/src/handlers/scheduledEventHandler.ts b/src/handlers/scheduledEventHandler.ts index 88dd2d0..9f2eb80 100644 --- a/src/handlers/scheduledEventHandler.ts +++ b/src/handlers/scheduledEventHandler.ts @@ -1,7 +1,7 @@ import { KVNamespace } from '@cloudflare/workers-types'; import { handleConfig } from '../config/config'; -import { DISCORD_NICKNAME_CHANGED_TIMESTAMP, NAMESPACE_NAME } from '../constants'; +import { NAMESPACE_NAME } from '../constants'; import { env, nicknameUpdateResponseType } from '../types/global.types'; import { generateJwt } from '../utils/generateJwt'; @@ -15,9 +15,9 @@ export async function callDiscordNicknameBatchUpdate(env: env) { const namespace = env[NAMESPACE_NAME] as unknown as KVNamespace; let lastNicknameUpdate: string | number | null = 0; try { - lastNicknameUpdate = await namespace.get(DISCORD_NICKNAME_CHANGED_TIMESTAMP); + lastNicknameUpdate = await namespace.get('DISCORD_NICKNAME_CHANGED'); if (lastNicknameUpdate === null) { - throw new Error('Error while fetching KV "DISCORD_NICKNAME_CHANGED_TIMESTAMP"'); + throw new Error('Error while fetching KV "DISCORD_NICKNAME_CHANGED" timestamp'); } } catch (err) { console.log('Error while fetching the timestamp for last nickname update'); @@ -51,7 +51,7 @@ export async function callDiscordNicknameBatchUpdate(env: env) { throw new Error("Error while trying to update users' discord nickname"); } try { - await namespace.put(DISCORD_NICKNAME_CHANGED_TIMESTAMP, Date.now().toString()); + await namespace.put('DISCORD_NICKNAME_CHANGED', Date.now().toString()); } catch (err) { console.log('Error while trying to update the last nickname change timestamp'); } From b856cbf0a995e055c165f5cfe48f7683193d5f25 Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Sat, 14 Oct 2023 14:36:29 +0530 Subject: [PATCH 11/45] refactor: rename CRON_JOBS_TIMESTAMP to CronJobsTimestamp --- src/constants.ts | 2 +- wrangler.toml | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/constants.ts b/src/constants.ts index c87b29d..9ab5017 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -1,3 +1,3 @@ -const NAMESPACE_NAME = 'CRON_JOBS_TIMESTAMPS'; +const NAMESPACE_NAME = 'CronJobsTimestamp'; export { NAMESPACE_NAME }; diff --git a/wrangler.toml b/wrangler.toml index 6dbc0e9..75d9df8 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -3,17 +3,17 @@ main = "src/worker.ts" compatibility_date = "2023-07-17" kv_namespaces = [ - { binding = "CRON_JOBS_TIMESTAMPS", id = "a5431887e6c94dc9b3e36c35a07081b9" } + { binding = "CronJobsTimestamp", id = "7dcf94601bec415db4b13d5d1faf0fc3" } ] # [env.staging] -# the BINDING_NAME must be CRON_JOBS_TIMESTAMPS to override in the staging env +# the BINDING_NAME must be CronJobsTimestamp to override in the staging env # kv_namespaces = [ # { binding = "", id = "" } # ] # [env.production] -# the BINDING_NAME must be CRON_JOBS_TIMESTAMPS to override in the production env +# the BINDING_NAME must be CronJobsTimestamp to override in the production env # kv_namespaces = [ # { binding = "", id = "" } # ] From bb2f61fee5de1fbdda76f6f0eff5f409e8565675 Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Sat, 14 Oct 2023 14:37:40 +0530 Subject: [PATCH 12/45] refactor: add console errors --- src/handlers/scheduledEventHandler.ts | 6 +++--- src/worker.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/handlers/scheduledEventHandler.ts b/src/handlers/scheduledEventHandler.ts index 9f2eb80..3671a2f 100644 --- a/src/handlers/scheduledEventHandler.ts +++ b/src/handlers/scheduledEventHandler.ts @@ -20,7 +20,7 @@ export async function callDiscordNicknameBatchUpdate(env: env) { throw new Error('Error while fetching KV "DISCORD_NICKNAME_CHANGED" timestamp'); } } catch (err) { - console.log('Error while fetching the timestamp for last nickname update'); + console.error(err, 'Error while fetching the timestamp for last nickname update'); throw err; } @@ -29,7 +29,7 @@ export async function callDiscordNicknameBatchUpdate(env: env) { try { token = await generateJwt(env); } catch (err) { - console.log(`Error while generating JWT token: ${err}`); + console.error(`Error while generating JWT token: ${err}`); throw err; } const response = await fetch(`${url.baseUrl}/discord-actions/nickname/status`, { @@ -53,7 +53,7 @@ export async function callDiscordNicknameBatchUpdate(env: env) { try { await namespace.put('DISCORD_NICKNAME_CHANGED', Date.now().toString()); } catch (err) { - console.log('Error while trying to update the last nickname change timestamp'); + console.error('Error while trying to update the last nickname change timestamp'); } return data; diff --git a/src/worker.ts b/src/worker.ts index 08040a2..7d43d70 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -13,7 +13,7 @@ export default { case '0 */6 * * *': return await callDiscordNicknameBatchUpdate(env); default: - console.log('Unknown Trigger Value!'); + console.error('Unknown Trigger Value!'); } }, // We need to keep all 3 parameters in this format even if they are not used as as cloudflare workers need them to be present So we are disabling eslint rule of no-unused-vars From 575a8fd48cbd989e60f4783ff51c5685422630c8 Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Sat, 14 Oct 2023 14:38:42 +0530 Subject: [PATCH 13/45] refactor: type name to PascalCase --- src/handlers/scheduledEventHandler.ts | 4 ++-- src/types/global.types.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/handlers/scheduledEventHandler.ts b/src/handlers/scheduledEventHandler.ts index 3671a2f..5fd4232 100644 --- a/src/handlers/scheduledEventHandler.ts +++ b/src/handlers/scheduledEventHandler.ts @@ -2,7 +2,7 @@ import { KVNamespace } from '@cloudflare/workers-types'; import { handleConfig } from '../config/config'; import { NAMESPACE_NAME } from '../constants'; -import { env, nicknameUpdateResponseType } from '../types/global.types'; +import { env, NicknameUpdateResponseType } from '../types/global.types'; import { generateJwt } from '../utils/generateJwt'; export async function ping(env: env) { @@ -46,7 +46,7 @@ export async function callDiscordNicknameBatchUpdate(env: env) { throw new Error("Error while trying to update users' discord nickname"); } - const data: nicknameUpdateResponseType = await response.json(); + const data: NicknameUpdateResponseType = await response.json(); if (data?.data.totalUsersStatus !== 0 && data?.data.successfulNicknameUpdates === 0) { throw new Error("Error while trying to update users' discord nickname"); } diff --git a/src/types/global.types.ts b/src/types/global.types.ts index 19cbd3f..69dcd12 100644 --- a/src/types/global.types.ts +++ b/src/types/global.types.ts @@ -2,7 +2,7 @@ export type env = { [key: string]: string; }; -export type nicknameUpdateResponseType = { +export type NicknameUpdateResponseType = { message: string; data: { totalUsersStatus: number; From c055577746b3040d81e70d1b662bbf08c6e4672d Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Sat, 14 Oct 2023 14:39:54 +0530 Subject: [PATCH 14/45] refactor: remove number from union type --- src/handlers/scheduledEventHandler.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/handlers/scheduledEventHandler.ts b/src/handlers/scheduledEventHandler.ts index 5fd4232..d60f562 100644 --- a/src/handlers/scheduledEventHandler.ts +++ b/src/handlers/scheduledEventHandler.ts @@ -13,7 +13,7 @@ export async function ping(env: env) { export async function callDiscordNicknameBatchUpdate(env: env) { const namespace = env[NAMESPACE_NAME] as unknown as KVNamespace; - let lastNicknameUpdate: string | number | null = 0; + let lastNicknameUpdate: string | null = '0'; try { lastNicknameUpdate = await namespace.get('DISCORD_NICKNAME_CHANGED'); if (lastNicknameUpdate === null) { From 2c6a49ff0c74ba5f6387e6e79773cb687a058433 Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Sat, 14 Oct 2023 15:40:22 +0530 Subject: [PATCH 15/45] refactor: log response after nickname update job --- src/handlers/scheduledEventHandler.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/handlers/scheduledEventHandler.ts b/src/handlers/scheduledEventHandler.ts index d60f562..e45f950 100644 --- a/src/handlers/scheduledEventHandler.ts +++ b/src/handlers/scheduledEventHandler.ts @@ -50,6 +50,9 @@ export async function callDiscordNicknameBatchUpdate(env: env) { if (data?.data.totalUsersStatus !== 0 && data?.data.successfulNicknameUpdates === 0) { throw new Error("Error while trying to update users' discord nickname"); } + + console.log(data); + try { await namespace.put('DISCORD_NICKNAME_CHANGED', Date.now().toString()); } catch (err) { From c9740789a02394a7de3f0262a9af963e87f9669b Mon Sep 17 00:00:00 2001 From: Bharati Subramanian Date: Sat, 14 Oct 2023 23:26:09 +0530 Subject: [PATCH 16/45] refactor: check for no value in KV store --- src/handlers/scheduledEventHandler.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/handlers/scheduledEventHandler.ts b/src/handlers/scheduledEventHandler.ts index e45f950..6fb7f50 100644 --- a/src/handlers/scheduledEventHandler.ts +++ b/src/handlers/scheduledEventHandler.ts @@ -19,6 +19,9 @@ export async function callDiscordNicknameBatchUpdate(env: env) { if (lastNicknameUpdate === null) { throw new Error('Error while fetching KV "DISCORD_NICKNAME_CHANGED" timestamp'); } + if (!lastNicknameUpdate) { + lastNicknameUpdate = '0'; + } } catch (err) { console.error(err, 'Error while fetching the timestamp for last nickname update'); throw err; From 47259cc75896e9caeb4f8f611d231da10dc2253d Mon Sep 17 00:00:00 2001 From: Prakash Date: Sat, 4 Nov 2023 01:24:16 +0530 Subject: [PATCH 17/45] define constants for cron string --- src/worker.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/worker.ts b/src/worker.ts index 7d43d70..1317e02 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -1,16 +1,19 @@ import { callDiscordNicknameBatchUpdate, ping } from './handlers/scheduledEventHandler'; import { env } from './types/global.types'; +const EVERY_4_HOURS = '0 */4 * * *'; +const EVERY_6_HOURS = '0 */6 * * *'; + export default { // We need to keep all 3 parameters in this format even if they are not used as as cloudflare workers need them to be present So we are disabling eslint rule of no-unused-vars // for more details read here: https://community.cloudflare.com/t/waituntil-is-not-a-function-when-using-workers-with-modules/375781/4 // eslint-disable-next-line no-unused-vars async scheduled(req: ScheduledController, env: env, ctx: ExecutionContext) { switch (req.cron) { - case '0 */4 * * *': + case EVERY_4_HOURS: ctx.waitUntil(ping(env)); break; - case '0 */6 * * *': + case EVERY_6_HOURS: return await callDiscordNicknameBatchUpdate(env); default: console.error('Unknown Trigger Value!'); From 3515c2e4659473ed05fd6dc301ef140e89e342a8 Mon Sep 17 00:00:00 2001 From: Prakash Date: Sat, 4 Nov 2023 01:33:06 +0530 Subject: [PATCH 18/45] change DISCORD_NICKNAME_CHANGED to DISCORD_NICKNAME_UPDATED_TIME --- src/handlers/scheduledEventHandler.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/handlers/scheduledEventHandler.ts b/src/handlers/scheduledEventHandler.ts index 6fb7f50..476c8f2 100644 --- a/src/handlers/scheduledEventHandler.ts +++ b/src/handlers/scheduledEventHandler.ts @@ -15,9 +15,9 @@ export async function callDiscordNicknameBatchUpdate(env: env) { const namespace = env[NAMESPACE_NAME] as unknown as KVNamespace; let lastNicknameUpdate: string | null = '0'; try { - lastNicknameUpdate = await namespace.get('DISCORD_NICKNAME_CHANGED'); + lastNicknameUpdate = await namespace.get('DISCORD_NICKNAME_UPDATED_TIME'); if (lastNicknameUpdate === null) { - throw new Error('Error while fetching KV "DISCORD_NICKNAME_CHANGED" timestamp'); + throw new Error('Error while fetching KV "DISCORD_NICKNAME_UPDATED_TIME" timestamp'); } if (!lastNicknameUpdate) { lastNicknameUpdate = '0'; @@ -57,7 +57,7 @@ export async function callDiscordNicknameBatchUpdate(env: env) { console.log(data); try { - await namespace.put('DISCORD_NICKNAME_CHANGED', Date.now().toString()); + await namespace.put('DISCORD_NICKNAME_UPDATED_TIME', Date.now().toString()); } catch (err) { console.error('Error while trying to update the last nickname change timestamp'); } From f054f7d5b68060630352f6242fb07a9b50b80e90 Mon Sep 17 00:00:00 2001 From: Prakash Date: Sat, 4 Nov 2023 01:38:34 +0530 Subject: [PATCH 19/45] remove disabled eslint rule --- src/worker.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/worker.ts b/src/worker.ts index 1317e02..219fd47 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -5,9 +5,6 @@ const EVERY_4_HOURS = '0 */4 * * *'; const EVERY_6_HOURS = '0 */6 * * *'; export default { - // We need to keep all 3 parameters in this format even if they are not used as as cloudflare workers need them to be present So we are disabling eslint rule of no-unused-vars - // for more details read here: https://community.cloudflare.com/t/waituntil-is-not-a-function-when-using-workers-with-modules/375781/4 - // eslint-disable-next-line no-unused-vars async scheduled(req: ScheduledController, env: env, ctx: ExecutionContext) { switch (req.cron) { case EVERY_4_HOURS: From 799b8d0e66d1cc6f2a312027743a911917b82bd7 Mon Sep 17 00:00:00 2001 From: Bharati Subramanian <51514137+bharati-21@users.noreply.github.com> Date: Wed, 15 Nov 2023 18:14:42 +0530 Subject: [PATCH 20/45] docs: add prod KV namespace ID --- wrangler.toml | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/wrangler.toml b/wrangler.toml index 75d9df8..dd66e15 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -12,11 +12,10 @@ kv_namespaces = [ # { binding = "", id = "" } # ] -# [env.production] -# the BINDING_NAME must be CronJobsTimestamp to override in the production env -# kv_namespaces = [ -# { binding = "", id = "" } -# ] +[env.production] +kv_namespaces = [ + { binding = "CronJobsTimestamp", id = "3a10f726c95d4afea9dee5fd00f029b9" } +] [triggers] crons = ["0 */4 * * *", "0 */6 * * *"] From 5718e0944eb2a356d1c306ff5ca2f3fa789a00f6 Mon Sep 17 00:00:00 2001 From: Ajeyakrishna <98796547+Ajeyakrishna-k@users.noreply.github.com> Date: Sun, 26 Nov 2023 22:48:15 +0530 Subject: [PATCH 21/45] Mock jwt functions and update GitHub workflow (#20) * fix: add npm test * feat: mocks jwt sign function * fix: lint issue * feat: add pull request template --- .github/pull_request_template.md | 33 +++++++++++++++++++++++ .github/workflows/test.yaml | 3 ++- __mocks__/@tsndr/cloudflare-worker-jwt.ts | 7 +++++ 3 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 .github/pull_request_template.md create mode 100644 __mocks__/@tsndr/cloudflare-worker-jwt.ts diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..fec9c6a --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,33 @@ +Date: `` + +Developer Name: `` + +---- + +## Issue Ticket Number:- +`` + +## Description: +`` + + +Is Under Feature Flag +- [ ] Yes +- [ ] No + +Database changes +- [ ] Yes +- [ ] No + +Breaking changes (If your feature is breaking/missing something please mention pending tickets) +- [ ] Yes +- [ ] No + +Is Development Tested? + +- [ ] Yes +- [ ] No + + +### Add relevant Screenshot below ( e.g test coverage etc. ) + diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 2737e68..26938c0 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -9,4 +9,5 @@ jobs: - uses: actions/checkout@v2 - run: npm install - run: npm run lint-check - - run: npm run format-check \ No newline at end of file + - run: npm run format-check + - run: npm run test \ No newline at end of file diff --git a/__mocks__/@tsndr/cloudflare-worker-jwt.ts b/__mocks__/@tsndr/cloudflare-worker-jwt.ts new file mode 100644 index 0000000..d90cca5 --- /dev/null +++ b/__mocks__/@tsndr/cloudflare-worker-jwt.ts @@ -0,0 +1,7 @@ +const mockJwt = { + sign: jest.fn().mockImplementation(() => { + return "SIGNED_JWT"; + }), +}; + +export default mockJwt; From 4f882dee285a860ff97949e99d5587649e992c40 Mon Sep 17 00:00:00 2001 From: Ajeyakrishna <98796547+Ajeyakrishna-k@users.noreply.github.com> Date: Tue, 28 Nov 2023 20:53:56 +0530 Subject: [PATCH 22/45] fix: adds npm install to github workflows (#21) --- .github/workflows/production.yaml | 1 + .github/workflows/staging.yaml | 1 + 2 files changed, 2 insertions(+) diff --git a/.github/workflows/production.yaml b/.github/workflows/production.yaml index 0bcec2f..3726aff 100644 --- a/.github/workflows/production.yaml +++ b/.github/workflows/production.yaml @@ -8,6 +8,7 @@ jobs: environment: production steps: - uses: actions/checkout@v2 + - run: npm install - uses: cloudflare/wrangler-action@2.0.0 with: apiToken: ${{secrets.CLOUDFLARE_API_TOKEN}} diff --git a/.github/workflows/staging.yaml b/.github/workflows/staging.yaml index 8f5956a..9cd7d68 100644 --- a/.github/workflows/staging.yaml +++ b/.github/workflows/staging.yaml @@ -8,6 +8,7 @@ jobs: environment: staging steps: - uses: actions/checkout@v2 + - run: npm install - uses: cloudflare/wrangler-action@2.0.0 with: apiToken: ${{secrets.CLOUDFLARE_API_TOKEN}} From 966c5095226680faef636cac292ede62ae317c83 Mon Sep 17 00:00:00 2001 From: Ajeyakrishna <98796547+Ajeyakrishna-k@users.noreply.github.com> Date: Thu, 30 Nov 2023 18:38:19 +0000 Subject: [PATCH 23/45] fix: updates staging kv namespace (#23) --- wrangler.toml | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/wrangler.toml b/wrangler.toml index dd66e15..dc032f7 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -2,16 +2,13 @@ name = "cron-jobs" main = "src/worker.ts" compatibility_date = "2023-07-17" + + +[env.staging] kv_namespaces = [ - { binding = "CronJobsTimestamp", id = "7dcf94601bec415db4b13d5d1faf0fc3" } + { binding = "CronJobsTimestamp", id = "509cd24483a24ddcb79f85f657274508" } ] -# [env.staging] -# the BINDING_NAME must be CronJobsTimestamp to override in the staging env -# kv_namespaces = [ -# { binding = "", id = "" } -# ] - [env.production] kv_namespaces = [ { binding = "CronJobsTimestamp", id = "3a10f726c95d4afea9dee5fd00f029b9" } From 94cbd5c56f118e62d419b5e651beb172ede51c65 Mon Sep 17 00:00:00 2001 From: Bharati Subramanian <51514137+bharati-21@users.noreply.github.com> Date: Tue, 12 Dec 2023 18:06:43 +0530 Subject: [PATCH 24/45] refactor: update timestamp only when no unsuccessful updates (#24) --- src/handlers/scheduledEventHandler.ts | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/handlers/scheduledEventHandler.ts b/src/handlers/scheduledEventHandler.ts index 476c8f2..5e4c4c0 100644 --- a/src/handlers/scheduledEventHandler.ts +++ b/src/handlers/scheduledEventHandler.ts @@ -50,17 +50,15 @@ export async function callDiscordNicknameBatchUpdate(env: env) { } const data: NicknameUpdateResponseType = await response.json(); - if (data?.data.totalUsersStatus !== 0 && data?.data.successfulNicknameUpdates === 0) { - throw new Error("Error while trying to update users' discord nickname"); + if (data?.data.unsuccessfulNicknameUpdates === 0) { + try { + await namespace.put('DISCORD_NICKNAME_UPDATED_TIME', Date.now().toString()); + } catch (err) { + console.error('Error while trying to update the last nickname change timestamp'); + } } console.log(data); - try { - await namespace.put('DISCORD_NICKNAME_UPDATED_TIME', Date.now().toString()); - } catch (err) { - console.error('Error while trying to update the last nickname change timestamp'); - } - return data; } From 248681367c02551b2940fa348a623f99aad57400 Mon Sep 17 00:00:00 2001 From: Ajeyakrishna <98796547+Ajeyakrishna-k@users.noreply.github.com> Date: Wed, 13 Dec 2023 03:06:46 +0530 Subject: [PATCH 25/45] Adds util functions and changes configs (#25) * fix: add npm test * feat: mocks jwt sign function * fix: lint issue * feat: add pull request template * feat: adds config and util functions --- src/config/config.ts | 37 ++++++++++++------- src/constants/commons.ts | 3 ++ src/constants/urls.ts | 7 ++++ src/tests/arrayUtils.test.ts | 35 ++++++++++++++++++ src/tests/generateJwt.test.ts | 69 ++++++++++++++++++++++++----------- src/types/global.types.ts | 28 +++++++++++++- src/utils/arrayUtils.ts | 19 ++++++++++ src/utils/generateJwt.ts | 15 ++++++++ wrangler.toml | 9 ++++- 9 files changed, 185 insertions(+), 37 deletions(-) create mode 100644 src/constants/commons.ts create mode 100644 src/constants/urls.ts create mode 100644 src/tests/arrayUtils.test.ts create mode 100644 src/utils/arrayUtils.ts diff --git a/src/config/config.ts b/src/config/config.ts index 48446f4..963c707 100644 --- a/src/config/config.ts +++ b/src/config/config.ts @@ -1,15 +1,26 @@ -import { env } from '../types/global.types'; +import { MISSED_UPDATES_DEVELOPMENT_ROLE_ID, MISSED_UPDATES_PROD_ROLE_ID, MISSED_UPDATES_STAGING_ROLE_ID } from '../constants/commons'; +import { RDS_BASE_API_URL, RDS_BASE_DEVELOPMENT_API_URL, RDS_BASE_STAGING_API_URL } from '../constants/urls'; +import { env, environment } from '../types/global.types'; -export const handleConfig = (env: env) => { - let baseUrl: string; - if (env.CURRENT_ENVIRONMENT) { - if (env.CURRENT_ENVIRONMENT.toLowerCase() === 'production') { - baseUrl = 'https://api.realdevsquad.com'; - } else { - baseUrl = 'https://staging-api.realdevsquad.com'; - } - } else { - baseUrl = 'https://staging-api.realdevsquad.com'; - } - return { baseUrl }; +const config = (env: env) => { + const environment: environment = { + production: { + RDS_BASE_API_URL: RDS_BASE_API_URL, + DISCORD_BOT_API_URL: env.DISCORD_BOT_API_URL, + MISSED_UPDATES_ROLE_ID: MISSED_UPDATES_PROD_ROLE_ID, + }, + staging: { + RDS_BASE_API_URL: RDS_BASE_STAGING_API_URL, + DISCORD_BOT_API_URL: env.DISCORD_BOT_API_URL, + MISSED_UPDATES_ROLE_ID: MISSED_UPDATES_STAGING_ROLE_ID, + }, + default: { + RDS_BASE_API_URL: RDS_BASE_DEVELOPMENT_API_URL, + DISCORD_BOT_API_URL: env.DISCORD_BOT_API_URL, + MISSED_UPDATES_ROLE_ID: MISSED_UPDATES_DEVELOPMENT_ROLE_ID, + }, + }; + + return environment[env.CURRENT_ENVIRONMENT] || environment.default; }; +export default config; diff --git a/src/constants/commons.ts b/src/constants/commons.ts new file mode 100644 index 0000000..77deb0f --- /dev/null +++ b/src/constants/commons.ts @@ -0,0 +1,3 @@ +export const MISSED_UPDATES_PROD_ROLE_ID = '1183553844811153458'; +export const MISSED_UPDATES_STAGING_ROLE_ID = '1183553844811153458'; +export const MISSED_UPDATES_DEVELOPMENT_ROLE_ID = '1181214205081296896'; diff --git a/src/constants/urls.ts b/src/constants/urls.ts new file mode 100644 index 0000000..013eeff --- /dev/null +++ b/src/constants/urls.ts @@ -0,0 +1,7 @@ +export const RDS_BASE_API_URL = 'https://api.realdevsquad.com'; +export const RDS_BASE_STAGING_API_URL = 'https://staging-api.realdevsquad.com'; +export const RDS_BASE_DEVELOPMENT_API_URL = 'http://localhost:3000'; // If needed, modify the URL to your local API server run through ngrok + +export const DISCORD_BOT_API_URL = 'env'; +export const DISCORD_BOT_STAGING_API_URL = ''; +export const DISCORD_BOT_DEVELOPMENT_API_URL = ''; diff --git a/src/tests/arrayUtils.test.ts b/src/tests/arrayUtils.test.ts new file mode 100644 index 0000000..ccf5515 --- /dev/null +++ b/src/tests/arrayUtils.test.ts @@ -0,0 +1,35 @@ +import { chunks } from '../utils/arrayUtils'; + +describe('chunks function', () => { + it('should return an empty array if size is less than 1', () => { + expect(chunks([1, 2, 3], 0)).toEqual([]); + }); + + it('should return an empty array if the input array is empty', () => { + expect(chunks([], 2)).toEqual([]); + }); + + it('should split the array into chunks of the specified size', () => { + const inputArray = [1, 2, 3, 4, 5, 6]; + const size = 2; + const expectedResult = [ + [1, 2], + [3, 4], + [5, 6], + ]; + expect(chunks(inputArray, size)).toEqual(expectedResult); + }); + + it('should split the array into chunks of size 1 if size is not specified', () => { + const inputArray = [1, 2, 3, 4, 5, 6]; + const expectedResult = [[1], [2], [3], [4], [5], [6]]; + expect(chunks(inputArray)).toEqual(expectedResult); + }); + + it('should not modify the original array', () => { + const inputArray = [1, 2, 3, 4, 5, 6]; + const size = 2; + chunks(inputArray, size); + expect(inputArray).toEqual(inputArray); + }); +}); diff --git a/src/tests/generateJwt.test.ts b/src/tests/generateJwt.test.ts index 57f2c31..4f412c1 100644 --- a/src/tests/generateJwt.test.ts +++ b/src/tests/generateJwt.test.ts @@ -1,9 +1,9 @@ import jwt from '@tsndr/cloudflare-worker-jwt'; -import { generateJwt } from '../utils/generateJwt'; +import { generateDiscordBotJwt, generateJwt } from '../utils/generateJwt'; import { privateKey } from './config/keys'; -describe('Mock test', () => { +describe('Generate Jwt', () => { let signSpy: jest.SpyInstance>; beforeEach(() => { signSpy = jest.spyOn(jwt, 'sign'); @@ -11,26 +11,53 @@ describe('Mock test', () => { afterEach(() => { signSpy.mockReset(); }); - test('Generate JWT function works', async () => { - signSpy.mockResolvedValue('Hello'); - const authToken = await generateJwt({ CRON_JOB_PRIVATE_KEY: privateKey }); - expect(authToken).not.toBeUndefined(); - }); - test('Should call sign method', async () => { - signSpy.mockResolvedValue('Hello'); - await generateJwt({ CRON_JOB_PRIVATE_KEY: privateKey }); - expect(signSpy).toBeCalledTimes(1); - }); - test('Should return promise without await', async () => { - signSpy.mockResolvedValue('Hello'); - const authToken = generateJwt({ CRON_JOB_PRIVATE_KEY: privateKey }); - expect(authToken).toBeInstanceOf(Promise); + describe('For Rds Backend', () => { + test('Generate JWT function works', async () => { + signSpy.mockResolvedValue('Hello'); + const authToken = await generateJwt({ CRON_JOB_PRIVATE_KEY: privateKey }); + expect(authToken).not.toBeUndefined(); + }); + test('Should call sign method', async () => { + signSpy.mockResolvedValue('Hello'); + await generateJwt({ CRON_JOB_PRIVATE_KEY: privateKey }); + expect(signSpy).toBeCalledTimes(1); + }); + test('Should return promise without await', async () => { + signSpy.mockResolvedValue('Hello'); + const authToken = generateJwt({ CRON_JOB_PRIVATE_KEY: privateKey }); + expect(authToken).toBeInstanceOf(Promise); + }); + test('Throws an error if generation fails', async () => { + signSpy.mockRejectedValue('Error'); + await generateJwt({ CRON_JOB_PRIVATE_KEY: privateKey }).catch((err) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toEqual('Error in generating the auth token'); + }); + }); }); - test('Throws an error if generation fails', async () => { - signSpy.mockRejectedValue('Error'); - await generateJwt({ CRON_JOB_PRIVATE_KEY: privateKey }).catch((err) => { - expect(err).toBeInstanceOf(Error); - expect(err.message).toEqual('Error in generating the auth token'); + + describe('For Discord Bot', () => { + test('Generate JWT function works', async () => { + signSpy.mockResolvedValue('Hello'); + const authToken = await generateDiscordBotJwt({ DISCORD_BOT_PRIVATE_KEY: privateKey }); + expect(authToken).not.toBeUndefined(); + }); + test('Should call sign method', async () => { + signSpy.mockResolvedValue('Hello'); + await generateDiscordBotJwt({ DISCORD_BOT_PRIVATE_KEY: privateKey }); + expect(signSpy).toBeCalledTimes(1); + }); + test('Should return promise without await', async () => { + signSpy.mockResolvedValue('Hello'); + const authToken = generateDiscordBotJwt({ DISCORD_BOT_PRIVATE_KEY: privateKey }); + expect(authToken).toBeInstanceOf(Promise); + }); + test('Throws an error if generation fails', async () => { + signSpy.mockRejectedValue('Error'); + await generateDiscordBotJwt({ DISCORD_BOT_PRIVATE_KEY: privateKey }).catch((err) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toEqual('Error in generating the auth token'); + }); }); }); }); diff --git a/src/types/global.types.ts b/src/types/global.types.ts index 69dcd12..6652346 100644 --- a/src/types/global.types.ts +++ b/src/types/global.types.ts @@ -1,5 +1,14 @@ export type env = { - [key: string]: string; + [key: string]: any; +}; + +export type environment = { + [key: string]: variables; +}; +export type variables = { + RDS_BASE_API_URL: string; + DISCORD_BOT_API_URL: string; + MISSED_UPDATES_ROLE_ID: string; }; export type NicknameUpdateResponseType = { @@ -10,3 +19,20 @@ export type NicknameUpdateResponseType = { unsuccessfulNicknameUpdates: number; }; }; + +export type DiscordUserIdList = { + usersToAddRole: string[]; + tasks: number; + missedUpdatesTasks: number; + cursor: string; +}; + +export interface DiscordUserRole { + userid: string; + roleid: string; +} +export type DiscordRoleUpdatedList = { + userid: string; + roleid: string; + success: boolean; +}; diff --git a/src/utils/arrayUtils.ts b/src/utils/arrayUtils.ts new file mode 100644 index 0000000..4df4943 --- /dev/null +++ b/src/utils/arrayUtils.ts @@ -0,0 +1,19 @@ +/** + * Creates an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements. + * description credit: https://lodash.com/docs/4.17.15#chunk + * source code inspiration https://youmightnotneed.com/lodash#chunk + * @param {array}: array to be splitted into groups + * @param {size}: size of array groups + * @return {array}: array of arrays of elements split into groups the length of size. + */ +export const chunks = (array: any[], size: number = 1): any[][] => { + if (!Array.isArray(array) || size < 1) { + return []; + } + const temp = [...array]; + const result = []; + while (temp.length) { + result.push(temp.splice(0, size)); + } + return result; +}; diff --git a/src/utils/generateJwt.ts b/src/utils/generateJwt.ts index 3581335..b086ae0 100644 --- a/src/utils/generateJwt.ts +++ b/src/utils/generateJwt.ts @@ -18,3 +18,18 @@ export const generateJwt = async (env: env) => { throw new Error('Error in generating the auth token'); } }; + +export const generateDiscordBotJwt = async (env: env) => { + try { + const authToken = await jwt.sign( + { + exp: Math.floor(Date.now() / 1000) + 2, + }, + env.DISCORD_BOT_PRIVATE_KEY, + { algorithm: 'RS256' }, + ); + return authToken; + } catch (err) { + throw new Error('Error in generating the auth token'); + } +}; diff --git a/wrangler.toml b/wrangler.toml index dc032f7..2d67b82 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -3,19 +3,24 @@ main = "src/worker.ts" compatibility_date = "2023-07-17" - [env.staging] kv_namespaces = [ { binding = "CronJobsTimestamp", id = "509cd24483a24ddcb79f85f657274508" } ] +services = [ + { binding = "DISCORD_BOT", service = "discord-slash-commands", environment = "staging" } +] [env.production] kv_namespaces = [ { binding = "CronJobsTimestamp", id = "3a10f726c95d4afea9dee5fd00f029b9" } ] +services = [ + { binding = "DISCORD_BOT", service = "discord-slash-commands", environment = "production" } +] [triggers] -crons = ["0 */4 * * *", "0 */6 * * *"] +crons = ["0 */4 * * *", "0 */6 * * *","0 */12 * * *" ] # # Durable Object binding - For more information: https://developers.cloudflare.com/workers/runtime-apis/durable-objects # [[durable_objects]] From 76bef03f37017ddfedbfe9e8a431b3f97ae52670 Mon Sep 17 00:00:00 2001 From: Ajeyakrishna Date: Thu, 14 Dec 2023 04:54:18 +0530 Subject: [PATCH 26/45] fix: changes old config syntax --- src/handlers/scheduledEventHandler.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/handlers/scheduledEventHandler.ts b/src/handlers/scheduledEventHandler.ts index 5e4c4c0..45dcc2e 100644 --- a/src/handlers/scheduledEventHandler.ts +++ b/src/handlers/scheduledEventHandler.ts @@ -1,13 +1,13 @@ import { KVNamespace } from '@cloudflare/workers-types'; -import { handleConfig } from '../config/config'; +import config from '../config/config'; import { NAMESPACE_NAME } from '../constants'; import { env, NicknameUpdateResponseType } from '../types/global.types'; import { generateJwt } from '../utils/generateJwt'; export async function ping(env: env) { - const url = handleConfig(env); - const response = await fetch(`${url.baseUrl}/healthcheck`); + const url = config(env).RDS_BASE_API_URL; + const response = await fetch(`${url}/healthcheck`); return response; } @@ -27,7 +27,7 @@ export async function callDiscordNicknameBatchUpdate(env: env) { throw err; } - const url = handleConfig(env); + const url = config(env).RDS_BASE_API_URL; let token; try { token = await generateJwt(env); @@ -35,7 +35,7 @@ export async function callDiscordNicknameBatchUpdate(env: env) { console.error(`Error while generating JWT token: ${err}`); throw err; } - const response = await fetch(`${url.baseUrl}/discord-actions/nickname/status`, { + const response = await fetch(`${url}/discord-actions/nickname/status`, { method: 'POST', headers: { Authorization: `Bearer ${token}`, From 3e7467509aef261985ff0116a4b370f59f6b3237 Mon Sep 17 00:00:00 2001 From: Ajeyakrishna <98796547+Ajeyakrishna-k@users.noreply.github.com> Date: Thu, 14 Dec 2023 23:25:27 +0530 Subject: [PATCH 27/45] chore: updates staging id (#31) --- wrangler.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wrangler.toml b/wrangler.toml index 2d67b82..a059c85 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -5,7 +5,7 @@ compatibility_date = "2023-07-17" [env.staging] kv_namespaces = [ - { binding = "CronJobsTimestamp", id = "509cd24483a24ddcb79f85f657274508" } + { binding = "CronJobsTimestamp", id = "6fbc191da931473393d5fbe612251d29" } ] services = [ { binding = "DISCORD_BOT", service = "discord-slash-commands", environment = "staging" } From 2bc79c1bbceac76a27b2a4a5adb26340bb32e6a4 Mon Sep 17 00:00:00 2001 From: Ajeyakrishna <98796547+Ajeyakrishna-k@users.noreply.github.com> Date: Fri, 15 Dec 2023 00:00:37 +0530 Subject: [PATCH 28/45] chore: adds kv namespace (#32) --- wrangler.toml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/wrangler.toml b/wrangler.toml index a059c85..e3761b6 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -2,7 +2,9 @@ name = "cron-jobs" main = "src/worker.ts" compatibility_date = "2023-07-17" - +kv_namespaces = [ + { binding = "CronJobsTimestamp", id = "6fbc191da931473393d5fbe612251d29" } +] [env.staging] kv_namespaces = [ { binding = "CronJobsTimestamp", id = "6fbc191da931473393d5fbe612251d29" } From 176690a2bafd11c3db1d638fabd7a7f6520112f6 Mon Sep 17 00:00:00 2001 From: Ajeyakrishna <98796547+Ajeyakrishna-k@users.noreply.github.com> Date: Fri, 15 Dec 2023 20:46:30 +0530 Subject: [PATCH 29/45] Adds cron job handler functions (#26) * fix: add npm test * feat: mocks jwt sign function * fix: lint issue * feat: add pull request template * feat: adds config and util functions * feat: adds cron tab and handler functions * chore: remove old code * fix: update cursor flow in get missed updates api * feat: update rds backend api response type --- src/handlers/scheduledEventHandler.ts | 39 +++++++++-- src/services/discordBotServices.ts | 27 ++++++++ src/services/rdsBackendService.ts | 32 +++++++++ src/tests/fixtures/missedRoleHandler.ts | 38 +++++++++++ src/tests/handlers/missedRoleHandler.test.ts | 67 +++++++++++++++++++ src/tests/services/discordBotService.test.ts | 49 ++++++++++++++ src/tests/services/rdsBackendService.test.ts | 68 ++++++++++++++++++++ src/types/global.types.ts | 5 +- src/worker.ts | 6 +- 9 files changed, 325 insertions(+), 6 deletions(-) create mode 100644 src/services/discordBotServices.ts create mode 100644 src/services/rdsBackendService.ts create mode 100644 src/tests/fixtures/missedRoleHandler.ts create mode 100644 src/tests/handlers/missedRoleHandler.test.ts create mode 100644 src/tests/services/discordBotService.test.ts create mode 100644 src/tests/services/rdsBackendService.test.ts diff --git a/src/handlers/scheduledEventHandler.ts b/src/handlers/scheduledEventHandler.ts index 45dcc2e..e5d81c8 100644 --- a/src/handlers/scheduledEventHandler.ts +++ b/src/handlers/scheduledEventHandler.ts @@ -2,7 +2,10 @@ import { KVNamespace } from '@cloudflare/workers-types'; import config from '../config/config'; import { NAMESPACE_NAME } from '../constants'; -import { env, NicknameUpdateResponseType } from '../types/global.types'; +import { updateUserRoles } from '../services/discordBotServices'; +import { getMissedUpdatesUsers } from '../services/rdsBackendService'; +import { DiscordUserRole, env, NicknameUpdateResponseType } from '../types/global.types'; +import { chunks } from '../utils/arrayUtils'; import { generateJwt } from '../utils/generateJwt'; export async function ping(env: env) { @@ -57,8 +60,36 @@ export async function callDiscordNicknameBatchUpdate(env: env) { console.error('Error while trying to update the last nickname change timestamp'); } } - - console.log(data); - return data; } + +export const addMissedUpdatesRole = async (env: env) => { + const MAX_ROLE_UPDATE = 25; + try { + let cursor: string | undefined = undefined; + for (let index = MAX_ROLE_UPDATE; index > 0; index--) { + if (index < MAX_ROLE_UPDATE && !cursor) break; + + const missedUpdatesUsers = await getMissedUpdatesUsers(env, cursor); + + if (!!missedUpdatesUsers && missedUpdatesUsers.usersToAddRole?.length > 1) { + const discordUserIdRoleIdList: DiscordUserRole[] = missedUpdatesUsers.usersToAddRole.map((userId) => ({ + userid: userId, + roleid: config(env).MISSED_UPDATES_ROLE_ID, + })); + + const discordUserRoleChunks = chunks(discordUserIdRoleIdList, MAX_ROLE_UPDATE); + for (const discordUserRoleList of discordUserRoleChunks) { + try { + await updateUserRoles(env, discordUserRoleList); + } catch (error) { + console.error('Error occurred while updating discord users', error); + } + } + } + cursor = missedUpdatesUsers?.cursor; + } + } catch (err) { + console.error('Error while adding missed updates roles'); + } +}; diff --git a/src/services/discordBotServices.ts b/src/services/discordBotServices.ts new file mode 100644 index 0000000..5550262 --- /dev/null +++ b/src/services/discordBotServices.ts @@ -0,0 +1,27 @@ +import config from '../config/config'; +import { DiscordRoleUpdatedList, DiscordUserRole, env } from '../types/global.types'; +import { generateDiscordBotJwt } from '../utils/generateJwt'; + +export const updateUserRoles = async (env: env, payload: DiscordUserRole[]): Promise => { + try { + const url = config(env).DISCORD_BOT_API_URL; + const token = await generateDiscordBotJwt(env); + + const response = await env.DISCORD_BOT.fetch(`${url}/roles?action=add-role`, { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(payload), + }); + if (!response.ok) { + throw Error(`Role Update failed with status: ${response.status}`); + } + const data: DiscordRoleUpdatedList = await response.json(); + return data; + } catch (error) { + console.error('Error while updating discord user roles'); + throw error; + } +}; diff --git a/src/services/rdsBackendService.ts b/src/services/rdsBackendService.ts new file mode 100644 index 0000000..695b0f8 --- /dev/null +++ b/src/services/rdsBackendService.ts @@ -0,0 +1,32 @@ +import config from '../config/config'; +import { DiscordUsersResponse, env } from '../types/global.types'; +import { generateJwt } from '../utils/generateJwt'; + +export const getMissedUpdatesUsers = async (env: env, cursor: string | undefined) => { + try { + const baseUrl = config(env).RDS_BASE_API_URL; + + const url = new URL(`${baseUrl}/tasks/users/discord`); + url.searchParams.append('q', 'status:missed-updates'); + if (cursor) { + url.searchParams.append('cursor', cursor); + } + const token = await generateJwt(env); + const response = await fetch(url, { + method: 'GET', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + }, + }); + if (!response.ok) { + throw new Error(`Fetch call to get user discord details failed with status: ${response.status}`); + } + + const responseData: DiscordUsersResponse = await response.json(); + return responseData?.data; + } catch (error) { + console.error('Error occurrent while fetching discord user details'); + throw error; + } +}; diff --git a/src/tests/fixtures/missedRoleHandler.ts b/src/tests/fixtures/missedRoleHandler.ts new file mode 100644 index 0000000..aba2b53 --- /dev/null +++ b/src/tests/fixtures/missedRoleHandler.ts @@ -0,0 +1,38 @@ +export const missedUpdatesUsersResponse = { + message: 'Discord details of users with status missed updates fetched successfully', + data: {}, +}; +export const missedUpdatesUsersMock = { + usersToAddRole: ['user1', 'user2'], + tasks: 10, + missedUpdatesTasks: 5, + cursor: 'some-cursor', +}; +export const missedUpdatesUsersMockWithNoUsers = { + usersToAddRole: [], + tasks: 10, + missedUpdatesTasks: 5, +}; +export const missedUpdatesUsersMockWithoutCursor = { + usersToAddRole: ['user1', 'user2'], + tasks: 10, + missedUpdatesTasks: 5, +}; + +export const updateRolesResponseMock = { + userid: 'user1', + roleid: '1', + success: true, +}; +export const discordUserRoleMock = [ + { userid: 'user1', roleid: '1' }, + { userid: 'user2', roleid: '2' }, +]; + +export const discordRoleUpdateResult = [ + { + userid: '1', + roleid: '2', + success: true, + }, +]; diff --git a/src/tests/handlers/missedRoleHandler.test.ts b/src/tests/handlers/missedRoleHandler.test.ts new file mode 100644 index 0000000..db8f233 --- /dev/null +++ b/src/tests/handlers/missedRoleHandler.test.ts @@ -0,0 +1,67 @@ +import { addMissedUpdatesRole } from '../../handlers/scheduledEventHandler'; +import { updateUserRoles } from '../../services/discordBotServices'; +import { getMissedUpdatesUsers } from '../../services/rdsBackendService'; +import { + missedUpdatesUsersMock, + missedUpdatesUsersMockWithNoUsers, + missedUpdatesUsersMockWithoutCursor, +} from '../fixtures/missedRoleHandler'; + +jest.mock('.../../../../services/rdsBackendService', () => ({ + getMissedUpdatesUsers: jest.fn(), +})); +jest.mock('.../../../../services/discordBotServices', () => ({ + updateUserRoles: jest.fn(), +})); +describe('addMissedUpdatesRole', () => { + beforeEach(() => { + jest.resetAllMocks(); + }); + afterEach(() => { + jest.clearAllMocks(); + }); + + it('should call getMissedUpdatesUsers and updateUserRoles when there are users to add role', async () => { + (getMissedUpdatesUsers as jest.Mock) + .mockResolvedValueOnce(missedUpdatesUsersMock) + .mockResolvedValueOnce(missedUpdatesUsersMockWithoutCursor); + await addMissedUpdatesRole({}); + expect(getMissedUpdatesUsers).toHaveBeenCalledTimes(2); + expect(updateUserRoles).toHaveBeenCalledTimes(2); + }); + + it('should not call updateUserRoles when there are no users to add role', async () => { + (getMissedUpdatesUsers as jest.Mock).mockResolvedValueOnce(missedUpdatesUsersMockWithNoUsers); + + await addMissedUpdatesRole({}); + expect(getMissedUpdatesUsers).toHaveBeenCalledTimes(1); + expect(updateUserRoles).toHaveBeenCalledTimes(0); + }); + + it('should create chunks of userId and update roles multiple times when count is greater than 25', async () => { + const mockValue: any = { ...missedUpdatesUsersMockWithoutCursor, usersToAddRole: new Array(75).fill('id') }; + (getMissedUpdatesUsers as jest.Mock).mockResolvedValueOnce(mockValue); + + await addMissedUpdatesRole({}); + expect(getMissedUpdatesUsers).toHaveBeenCalledTimes(1); + expect(updateUserRoles).toHaveBeenCalledTimes(3); + }); + + it('should handle errors', async () => { + (getMissedUpdatesUsers as jest.Mock).mockRejectedValueOnce(new Error('Error fetching missed updates users')); + const consoleSpy = jest.spyOn(console, 'error'); + await addMissedUpdatesRole({}); + expect(consoleSpy).toHaveBeenCalledWith('Error while adding missed updates roles'); + }); + + it('should continue updating user roles even when a call fails', async () => { + (updateUserRoles as jest.Mock).mockRejectedValueOnce(new Error('Error occurred')); + const consoleSpy = jest.spyOn(console, 'error'); + const mockValue: any = { ...missedUpdatesUsersMockWithoutCursor, usersToAddRole: new Array(75).fill('id') }; + (getMissedUpdatesUsers as jest.Mock).mockResolvedValueOnce(mockValue); + await addMissedUpdatesRole({}); + expect(getMissedUpdatesUsers).toHaveBeenCalledTimes(1); + expect(consoleSpy).toHaveBeenCalledTimes(1); + expect(updateUserRoles).toHaveBeenCalledTimes(3); + }); +}); diff --git a/src/tests/services/discordBotService.test.ts b/src/tests/services/discordBotService.test.ts new file mode 100644 index 0000000..27251b7 --- /dev/null +++ b/src/tests/services/discordBotService.test.ts @@ -0,0 +1,49 @@ +import config from '../../config/config'; +import { updateUserRoles } from '../../services/discordBotServices'; +import { discordRoleUpdateResult, discordUserRoleMock } from '../fixtures/missedRoleHandler'; + +jest.mock('../../utils/generateJwt', () => ({ + generateDiscordBotJwt: jest.fn().mockResolvedValueOnce('mocked-jwt-token'), +})); +describe('discordBotService', () => { + describe('updateUserRoles', () => { + let fetchSpy: jest.Mock; + beforeEach(() => { + fetchSpy = jest.fn(); + jest.clearAllMocks(); + }); + + it('should make a successful API call and return the expected data', async () => { + fetchSpy.mockResolvedValueOnce({ + ok: true, + status: 200, + json: jest.fn().mockResolvedValueOnce(discordRoleUpdateResult), + } as unknown as Response); + const result = await updateUserRoles({ DISCORD_BOT: { fetch: fetchSpy } }, discordUserRoleMock); + + expect(fetchSpy).toHaveBeenCalledWith(`${config({}).DISCORD_BOT_API_URL}/roles?action=add-role`, { + method: 'POST', + headers: { + Authorization: 'Bearer mocked-jwt-token', + 'Content-Type': 'application/json', + }, + body: JSON.stringify(discordUserRoleMock), + }); + expect(result).toEqual([...discordRoleUpdateResult]); + }); + + it('should throw error when api call fails', async () => { + fetchSpy.mockResolvedValueOnce({ + ok: false, + status: 400, + } as unknown as Response); + await expect(updateUserRoles({ DISCORD_BOT: { fetch: fetchSpy } }, [])).rejects.toThrow('Role Update failed with status: 400'); + }); + it('should handle unknown errors', async () => { + const consoleSpy = jest.spyOn(console, 'error'); + fetchSpy.mockRejectedValueOnce(new Error('Error occurred')); + await expect(updateUserRoles({ DISCORD_BOT: { fetch: fetchSpy } }, [])).rejects.toThrow('Error occurred'); + expect(consoleSpy).toHaveBeenCalledWith('Error while updating discord user roles'); + }); + }); +}); diff --git a/src/tests/services/rdsBackendService.test.ts b/src/tests/services/rdsBackendService.test.ts new file mode 100644 index 0000000..cbf1a28 --- /dev/null +++ b/src/tests/services/rdsBackendService.test.ts @@ -0,0 +1,68 @@ +import config from '../../config/config'; +import { getMissedUpdatesUsers } from '../../services/rdsBackendService'; +import { missedUpdatesUsersMock, missedUpdatesUsersResponse } from '../fixtures/missedRoleHandler'; + +jest.mock('../../utils/generateJwt', () => ({ + generateJwt: jest.fn().mockResolvedValue('mocked-jwt-token'), +})); + +describe('rdsBackendService', () => { + describe('updateUserRoles', () => { + let cursor: undefined | string; + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('should make a successful API call and return the expected data', async () => { + jest.spyOn(global, 'fetch').mockResolvedValueOnce({ + ok: true, + status: 200, + json: jest.fn().mockResolvedValueOnce({ ...missedUpdatesUsersResponse, data: missedUpdatesUsersMock }), + } as unknown as Response); + const result = await getMissedUpdatesUsers({}, cursor); + const url = new URL(`${config({}).RDS_BASE_API_URL}/tasks/users/discord`); + url.searchParams.append('q', 'status:missed-updates'); + expect(fetch).toHaveBeenCalledWith(url, { + method: 'GET', + headers: { + Authorization: 'Bearer mocked-jwt-token', + 'Content-Type': 'application/json', + }, + }); + expect(result).toEqual({ ...missedUpdatesUsersMock }); + }); + it('should make a successful API call with cursor', async () => { + jest.spyOn(global, 'fetch').mockResolvedValueOnce({ + ok: true, + status: 200, + json: jest.fn().mockResolvedValueOnce({ ...missedUpdatesUsersResponse, data: missedUpdatesUsersMock }), + } as unknown as Response); + const result = await getMissedUpdatesUsers({}, 'cursorValue'); + const url = new URL(`${config({}).RDS_BASE_API_URL}/tasks/users/discord`); + url.searchParams.append('q', 'status:missed-updates'); + url.searchParams.append('cursor', 'cursorValue'); + expect(fetch).toHaveBeenCalledWith(url, { + method: 'GET', + headers: { + Authorization: 'Bearer mocked-jwt-token', + 'Content-Type': 'application/json', + }, + }); + expect(result).toEqual({ ...missedUpdatesUsersMock }); + }); + it('should throw error when api call fails', async () => { + jest.spyOn(global, 'fetch').mockResolvedValueOnce({ + ok: false, + status: 400, + } as unknown as Response); + await expect(getMissedUpdatesUsers({}, cursor)).rejects.toThrow('Fetch call to get user discord details failed with status: 400'); + }); + + it('should handle unknown errors', async () => { + const consoleSpy = jest.spyOn(console, 'error'); + jest.spyOn(global, 'fetch').mockRejectedValueOnce(new Error('Error occurred')); + await expect(getMissedUpdatesUsers({}, cursor)).rejects.toThrow('Error occurred'); + expect(consoleSpy).toHaveBeenCalledWith('Error occurrent while fetching discord user details'); + }); + }); +}); diff --git a/src/types/global.types.ts b/src/types/global.types.ts index 6652346..ac46191 100644 --- a/src/types/global.types.ts +++ b/src/types/global.types.ts @@ -19,7 +19,10 @@ export type NicknameUpdateResponseType = { unsuccessfulNicknameUpdates: number; }; }; - +export type DiscordUsersResponse = { + message: string; + data: DiscordUserIdList; +}; export type DiscordUserIdList = { usersToAddRole: string[]; tasks: number; diff --git a/src/worker.ts b/src/worker.ts index 219fd47..c1daf9a 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -1,8 +1,9 @@ -import { callDiscordNicknameBatchUpdate, ping } from './handlers/scheduledEventHandler'; +import { addMissedUpdatesRole, callDiscordNicknameBatchUpdate, ping } from './handlers/scheduledEventHandler'; import { env } from './types/global.types'; const EVERY_4_HOURS = '0 */4 * * *'; const EVERY_6_HOURS = '0 */6 * * *'; +const EVERY_12_HOURS = '0 */12 * * *'; export default { async scheduled(req: ScheduledController, env: env, ctx: ExecutionContext) { @@ -12,6 +13,9 @@ export default { break; case EVERY_6_HOURS: return await callDiscordNicknameBatchUpdate(env); + case EVERY_12_HOURS: { + return await addMissedUpdatesRole(env); + } default: console.error('Unknown Trigger Value!'); } From 9d19c35db32462eaef261808511a86069b7ce84a Mon Sep 17 00:00:00 2001 From: Ajeyakrishna <98796547+Ajeyakrishna-k@users.noreply.github.com> Date: Sat, 16 Dec 2023 00:03:19 +0530 Subject: [PATCH 30/45] test: kv namespace for staging (#33) --- wrangler.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wrangler.toml b/wrangler.toml index e3761b6..08217c1 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -3,7 +3,7 @@ main = "src/worker.ts" compatibility_date = "2023-07-17" kv_namespaces = [ - { binding = "CronJobsTimestamp", id = "6fbc191da931473393d5fbe612251d29" } + { binding = "CronJobsTimestamp", id = "1234" } ] [env.staging] kv_namespaces = [ From 16765a96aeb9fff38ad448f7fe6a2790b1ab36e9 Mon Sep 17 00:00:00 2001 From: Prakash Choudhary <34452139+prakashchoudhary07@users.noreply.github.com> Date: Sat, 16 Dec 2023 00:53:20 +0530 Subject: [PATCH 31/45] Update staging.yaml, added staging env, other secrets (#34) --- .github/workflows/staging.yaml | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/.github/workflows/staging.yaml b/.github/workflows/staging.yaml index 9cd7d68..c4bb0bb 100644 --- a/.github/workflows/staging.yaml +++ b/.github/workflows/staging.yaml @@ -9,15 +9,22 @@ jobs: steps: - uses: actions/checkout@v2 - run: npm install - - uses: cloudflare/wrangler-action@2.0.0 + - uses: cloudflare/wrangler-action@v3 with: apiToken: ${{secrets.CLOUDFLARE_API_TOKEN}} accountId: ${{secrets.CLOUDFLARE_ACCOUNT_ID}} + command: deploy --env=${{ vars.CURRENT_ENVIRONMENT }} secrets: | - CRON_JOB_PRIVATE_KEY CURRENT_ENVIRONMENT + CRON_JOB_PRIVATE_KEY + DISCORD_BOT_PRIVATE_KEY + DISCORD_BOT_API_URL env: - CURRENT_ENVIRONMENT: staging - CRON_JOB_PRIVATE_KEY: ${{secrets.CRON_JOB_PRIVATE_KEY}} CLOUDFLARE_API_TOKEN: ${{secrets.CLOUDFLARE_API_TOKEN}} CLOUDFLARE_ACCOUNT_ID: ${{secrets.CLOUDFLARE_ACCOUNT_ID}} + CURRENT_ENVIRONMENT: ${{vars.CURRENT_ENVIRONMENT}} + CRON_JOB_PRIVATE_KEY: ${{secrets.CRON_JOB_PRIVATE_KEY}} + DISCORD_BOT_PRIVATE_KEY: ${{secrets.DISCORD_BOT_PRIVATE_KEY}} + DISCORD_BOT_API_URL: ${{secrets.DISCORD_BOT_API_URL}} + + From 90d8c43e51a7cf6ad386651c4ba956cf4937a593 Mon Sep 17 00:00:00 2001 From: Ajeyakrishna <98796547+Ajeyakrishna-k@users.noreply.github.com> Date: Sat, 16 Dec 2023 01:28:13 +0530 Subject: [PATCH 32/45] Update wrangler config for service binding (#35) * fix/service binding changes * refactor: updates wrangler environment for service binding --- wrangler.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wrangler.toml b/wrangler.toml index 08217c1..2af8848 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -10,7 +10,7 @@ kv_namespaces = [ { binding = "CronJobsTimestamp", id = "6fbc191da931473393d5fbe612251d29" } ] services = [ - { binding = "DISCORD_BOT", service = "discord-slash-commands", environment = "staging" } + { binding = "DISCORD_BOT", service = "discord-slash-commands" } ] [env.production] @@ -18,7 +18,7 @@ kv_namespaces = [ { binding = "CronJobsTimestamp", id = "3a10f726c95d4afea9dee5fd00f029b9" } ] services = [ - { binding = "DISCORD_BOT", service = "discord-slash-commands", environment = "production" } + { binding = "DISCORD_BOT", service = "discord-slash-commands" } ] [triggers] From b0011d383a52e8d0dc5379837d42770994a68088 Mon Sep 17 00:00:00 2001 From: Ajeyakrishna <98796547+Ajeyakrishna-k@users.noreply.github.com> Date: Sat, 16 Dec 2023 01:49:35 +0530 Subject: [PATCH 33/45] Removes 4hr cron trigger (#36) * fix/service binding changes * refactor: updates wrangler environment for service binding * fix: removes 4hr cron --------- Co-authored-by: Prakash Choudhary <34452139+prakashchoudhary07@users.noreply.github.com> --- src/worker.ts | 10 ++++------ wrangler.toml | 2 +- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/worker.ts b/src/worker.ts index c1daf9a..ea872dd 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -1,18 +1,16 @@ -import { addMissedUpdatesRole, callDiscordNicknameBatchUpdate, ping } from './handlers/scheduledEventHandler'; +import { addMissedUpdatesRole, callDiscordNicknameBatchUpdate } from './handlers/scheduledEventHandler'; import { env } from './types/global.types'; -const EVERY_4_HOURS = '0 */4 * * *'; const EVERY_6_HOURS = '0 */6 * * *'; const EVERY_12_HOURS = '0 */12 * * *'; export default { + // eslint-disable-next-line no-unused-vars async scheduled(req: ScheduledController, env: env, ctx: ExecutionContext) { switch (req.cron) { - case EVERY_4_HOURS: - ctx.waitUntil(ping(env)); - break; - case EVERY_6_HOURS: + case EVERY_6_HOURS: { return await callDiscordNicknameBatchUpdate(env); + } case EVERY_12_HOURS: { return await addMissedUpdatesRole(env); } diff --git a/wrangler.toml b/wrangler.toml index 2af8848..da44cc5 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -22,7 +22,7 @@ services = [ ] [triggers] -crons = ["0 */4 * * *", "0 */6 * * *","0 */12 * * *" ] +crons = ["0 */6 * * *","0 */12 * * *" ] # # Durable Object binding - For more information: https://developers.cloudflare.com/workers/runtime-apis/durable-objects # [[durable_objects]] From d402821edce2a3bfc76ae3101384d2133c09a7f2 Mon Sep 17 00:00:00 2001 From: Prakash Choudhary <34452139+prakashchoudhary07@users.noreply.github.com> Date: Sat, 16 Dec 2023 02:11:43 +0530 Subject: [PATCH 34/45] chore: add new secrets/vars to cf from github secrets/vars (#37) --- .github/workflows/production.yaml | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/.github/workflows/production.yaml b/.github/workflows/production.yaml index 3726aff..1a71356 100644 --- a/.github/workflows/production.yaml +++ b/.github/workflows/production.yaml @@ -7,17 +7,22 @@ jobs: runs-on: ubuntu-latest environment: production steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - run: npm install - - uses: cloudflare/wrangler-action@2.0.0 + - uses: cloudflare/wrangler-action@v3 with: apiToken: ${{secrets.CLOUDFLARE_API_TOKEN}} accountId: ${{secrets.CLOUDFLARE_ACCOUNT_ID}} + command: deploy --env=${{ vars.CURRENT_ENVIRONMENT }} secrets: | - CRON_JOB_PRIVATE_KEY CURRENT_ENVIRONMENT + CRON_JOB_PRIVATE_KEY + DISCORD_BOT_PRIVATE_KEY + DISCORD_BOT_API_URL env: - CURRENT_ENVIRONMENT: production - CRON_JOB_PRIVATE_KEY: ${{secrets.CRON_JOB_PRIVATE_KEY}} CLOUDFLARE_API_TOKEN: ${{secrets.CLOUDFLARE_API_TOKEN}} CLOUDFLARE_ACCOUNT_ID: ${{secrets.CLOUDFLARE_ACCOUNT_ID}} + CURRENT_ENVIRONMENT: ${{vars.CURRENT_ENVIRONMENT}} + CRON_JOB_PRIVATE_KEY: ${{secrets.CRON_JOB_PRIVATE_KEY}} + DISCORD_BOT_PRIVATE_KEY: ${{secrets.DISCORD_BOT_PRIVATE_KEY}} + DISCORD_BOT_API_URL: ${{secrets.DISCORD_BOT_API_URL}} From 39d93bc999ed9c5a9b27c76db79e1043b05a0ec6 Mon Sep 17 00:00:00 2001 From: Prakash Choudhary <34452139+prakashchoudhary07@users.noreply.github.com> Date: Sat, 16 Dec 2023 03:05:52 +0530 Subject: [PATCH 35/45] HOTFIX: update wrangler.toml --- wrangler.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wrangler.toml b/wrangler.toml index da44cc5..9157e82 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -15,7 +15,7 @@ services = [ [env.production] kv_namespaces = [ - { binding = "CronJobsTimestamp", id = "3a10f726c95d4afea9dee5fd00f029b9" } + { binding = "CronJobsTimestamp", id = "6fbc191da931473393d5fbe612251d29" } ] services = [ { binding = "DISCORD_BOT", service = "discord-slash-commands" } From c3f1ccc2ef9e4f963668cd03a8003548e6f84621 Mon Sep 17 00:00:00 2001 From: Prakash Choudhary <34452139+prakashchoudhary07@users.noreply.github.com> Date: Sat, 16 Dec 2023 03:15:26 +0530 Subject: [PATCH 36/45] chore: change checkout action to v3 --- .github/workflows/staging.yaml | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/.github/workflows/staging.yaml b/.github/workflows/staging.yaml index c4bb0bb..a263400 100644 --- a/.github/workflows/staging.yaml +++ b/.github/workflows/staging.yaml @@ -5,9 +5,9 @@ on: jobs: Deploy-to-Cloudflare: runs-on: ubuntu-latest - environment: staging + environment: production steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - run: npm install - uses: cloudflare/wrangler-action@v3 with: @@ -26,5 +26,3 @@ jobs: CRON_JOB_PRIVATE_KEY: ${{secrets.CRON_JOB_PRIVATE_KEY}} DISCORD_BOT_PRIVATE_KEY: ${{secrets.DISCORD_BOT_PRIVATE_KEY}} DISCORD_BOT_API_URL: ${{secrets.DISCORD_BOT_API_URL}} - - From 770c8490e6ed3cd7c41545ef817aa969cd0fc5d9 Mon Sep 17 00:00:00 2001 From: Prakash Choudhary <34452139+prakashchoudhary07@users.noreply.github.com> Date: Sat, 16 Dec 2023 03:22:38 +0530 Subject: [PATCH 37/45] chore: update env to staging --- .github/workflows/staging.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/staging.yaml b/.github/workflows/staging.yaml index a263400..7f23c3c 100644 --- a/.github/workflows/staging.yaml +++ b/.github/workflows/staging.yaml @@ -5,7 +5,7 @@ on: jobs: Deploy-to-Cloudflare: runs-on: ubuntu-latest - environment: production + environment: staging steps: - uses: actions/checkout@v3 - run: npm install From c3c5e789ab731bf05ef034be3c9854a590520a95 Mon Sep 17 00:00:00 2001 From: Prakash Choudhary <34452139+prakashchoudhary07@users.noreply.github.com> Date: Sat, 16 Dec 2023 03:39:25 +0530 Subject: [PATCH 38/45] chore: downgrade wrangler action and add env (#39) --- .github/workflows/staging.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/staging.yaml b/.github/workflows/staging.yaml index 7f23c3c..f982472 100644 --- a/.github/workflows/staging.yaml +++ b/.github/workflows/staging.yaml @@ -9,10 +9,11 @@ jobs: steps: - uses: actions/checkout@v3 - run: npm install - - uses: cloudflare/wrangler-action@v3 + - uses: cloudflare/wrangler-action@2.0.0 with: apiToken: ${{secrets.CLOUDFLARE_API_TOKEN}} accountId: ${{secrets.CLOUDFLARE_ACCOUNT_ID}} + environment: staging command: deploy --env=${{ vars.CURRENT_ENVIRONMENT }} secrets: | CURRENT_ENVIRONMENT From edeb9fb191d824eac2054d8e568f332d7328d004 Mon Sep 17 00:00:00 2001 From: Prakash Choudhary <34452139+prakashchoudhary07@users.noreply.github.com> Date: Sat, 16 Dec 2023 03:45:08 +0530 Subject: [PATCH 39/45] chore: upgreder cf actions (#40) --- .github/workflows/staging.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/staging.yaml b/.github/workflows/staging.yaml index f982472..d9e2a01 100644 --- a/.github/workflows/staging.yaml +++ b/.github/workflows/staging.yaml @@ -9,12 +9,12 @@ jobs: steps: - uses: actions/checkout@v3 - run: npm install - - uses: cloudflare/wrangler-action@2.0.0 + - uses: cloudflare/wrangler-action@v3 with: apiToken: ${{secrets.CLOUDFLARE_API_TOKEN}} accountId: ${{secrets.CLOUDFLARE_ACCOUNT_ID}} environment: staging - command: deploy --env=${{ vars.CURRENT_ENVIRONMENT }} + command: deploy --env ${{ vars.CURRENT_ENVIRONMENT }} secrets: | CURRENT_ENVIRONMENT CRON_JOB_PRIVATE_KEY From 64efeec70d2ff2a22e02402dd727217a25066d73 Mon Sep 17 00:00:00 2001 From: Prakash Choudhary <34452139+prakashchoudhary07@users.noreply.github.com> Date: Sat, 16 Dec 2023 03:59:13 +0530 Subject: [PATCH 40/45] chore: update github actions for prod and staging, added env (#41) --- .github/workflows/production.yaml | 7 ++++--- .github/workflows/staging.yaml | 6 +++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/.github/workflows/production.yaml b/.github/workflows/production.yaml index 1a71356..9a00414 100644 --- a/.github/workflows/production.yaml +++ b/.github/workflows/production.yaml @@ -1,11 +1,11 @@ -name: Deploy to production +name: Deploy to ${{ vars.CURRENT_ENVIRONMENT }} on: push: branches: main jobs: Deploy-to-Cloudflare: runs-on: ubuntu-latest - environment: production + environment: ${{ vars.CURRENT_ENVIRONMENT }} steps: - uses: actions/checkout@v3 - run: npm install @@ -13,7 +13,8 @@ jobs: with: apiToken: ${{secrets.CLOUDFLARE_API_TOKEN}} accountId: ${{secrets.CLOUDFLARE_ACCOUNT_ID}} - command: deploy --env=${{ vars.CURRENT_ENVIRONMENT }} + environment: ${{ vars.CURRENT_ENVIRONMENT }} + command: deploy --env ${{ vars.CURRENT_ENVIRONMENT }} secrets: | CURRENT_ENVIRONMENT CRON_JOB_PRIVATE_KEY diff --git a/.github/workflows/staging.yaml b/.github/workflows/staging.yaml index d9e2a01..d056a81 100644 --- a/.github/workflows/staging.yaml +++ b/.github/workflows/staging.yaml @@ -1,11 +1,11 @@ -name: Deploy to staging +name: Deploy to ${{ vars.CURRENT_ENVIRONMENT }} on: push: branches: develop jobs: Deploy-to-Cloudflare: runs-on: ubuntu-latest - environment: staging + environment: ${{ vars.CURRENT_ENVIRONMENT }} steps: - uses: actions/checkout@v3 - run: npm install @@ -13,7 +13,7 @@ jobs: with: apiToken: ${{secrets.CLOUDFLARE_API_TOKEN}} accountId: ${{secrets.CLOUDFLARE_ACCOUNT_ID}} - environment: staging + environment: ${{ vars.CURRENT_ENVIRONMENT }} command: deploy --env ${{ vars.CURRENT_ENVIRONMENT }} secrets: | CURRENT_ENVIRONMENT From 75d6ca8c8da8981d43b62b46f711fdef016a0ec8 Mon Sep 17 00:00:00 2001 From: Ajeyakrishna <98796547+Ajeyakrishna-k@users.noreply.github.com> Date: Sat, 16 Dec 2023 04:06:57 +0530 Subject: [PATCH 41/45] chore: rename workflow name (#43) --- .github/workflows/production.yaml | 2 +- .github/workflows/staging.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/production.yaml b/.github/workflows/production.yaml index 9a00414..4caae41 100644 --- a/.github/workflows/production.yaml +++ b/.github/workflows/production.yaml @@ -1,4 +1,4 @@ -name: Deploy to ${{ vars.CURRENT_ENVIRONMENT }} +name: Deploy to production on: push: branches: main diff --git a/.github/workflows/staging.yaml b/.github/workflows/staging.yaml index d056a81..4f06012 100644 --- a/.github/workflows/staging.yaml +++ b/.github/workflows/staging.yaml @@ -1,4 +1,4 @@ -name: Deploy to ${{ vars.CURRENT_ENVIRONMENT }} +name: Deploy to staging on: push: branches: develop From 61d7ef3ba2a73ff1498b9b1aeeb808e1c1a7baf9 Mon Sep 17 00:00:00 2001 From: Ajeyakrishna <98796547+Ajeyakrishna-k@users.noreply.github.com> Date: Sat, 16 Dec 2023 04:13:22 +0530 Subject: [PATCH 42/45] Updates workflow name (#44) * chore: rename workflow name * refactor: change env name --- .github/workflows/production.yaml | 2 +- .github/workflows/staging.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/production.yaml b/.github/workflows/production.yaml index 4caae41..eb66c69 100644 --- a/.github/workflows/production.yaml +++ b/.github/workflows/production.yaml @@ -5,7 +5,7 @@ on: jobs: Deploy-to-Cloudflare: runs-on: ubuntu-latest - environment: ${{ vars.CURRENT_ENVIRONMENT }} + environment: production steps: - uses: actions/checkout@v3 - run: npm install diff --git a/.github/workflows/staging.yaml b/.github/workflows/staging.yaml index 4f06012..d187439 100644 --- a/.github/workflows/staging.yaml +++ b/.github/workflows/staging.yaml @@ -5,7 +5,7 @@ on: jobs: Deploy-to-Cloudflare: runs-on: ubuntu-latest - environment: ${{ vars.CURRENT_ENVIRONMENT }} + environment: staging steps: - uses: actions/checkout@v3 - run: npm install From 0526f0f265d75199579891852a4b7f958b7c322d Mon Sep 17 00:00:00 2001 From: Ajeyakrishna <98796547+Ajeyakrishna-k@users.noreply.github.com> Date: Sat, 16 Dec 2023 04:22:20 +0530 Subject: [PATCH 43/45] chore: update kv namespace id for prod (#42) Co-authored-by: Prakash Choudhary <34452139+prakashchoudhary07@users.noreply.github.com> --- wrangler.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wrangler.toml b/wrangler.toml index 9157e82..da44cc5 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -15,7 +15,7 @@ services = [ [env.production] kv_namespaces = [ - { binding = "CronJobsTimestamp", id = "6fbc191da931473393d5fbe612251d29" } + { binding = "CronJobsTimestamp", id = "3a10f726c95d4afea9dee5fd00f029b9" } ] services = [ { binding = "DISCORD_BOT", service = "discord-slash-commands" } From 6d56dd7023f9b1b16548e169d9ec8c8d037d9a03 Mon Sep 17 00:00:00 2001 From: Ajeyakrishna Date: Mon, 18 Dec 2023 05:54:44 +0530 Subject: [PATCH 44/45] chore: change cron trigger time --- src/worker.ts | 4 ++-- wrangler.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/worker.ts b/src/worker.ts index ea872dd..60bd74d 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -2,7 +2,7 @@ import { addMissedUpdatesRole, callDiscordNicknameBatchUpdate } from './handlers import { env } from './types/global.types'; const EVERY_6_HOURS = '0 */6 * * *'; -const EVERY_12_HOURS = '0 */12 * * *'; +const EVERY_11_HOURS = '0 */11 * * *'; export default { // eslint-disable-next-line no-unused-vars @@ -11,7 +11,7 @@ export default { case EVERY_6_HOURS: { return await callDiscordNicknameBatchUpdate(env); } - case EVERY_12_HOURS: { + case EVERY_11_HOURS: { return await addMissedUpdatesRole(env); } default: diff --git a/wrangler.toml b/wrangler.toml index da44cc5..2162ea7 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -22,7 +22,7 @@ services = [ ] [triggers] -crons = ["0 */6 * * *","0 */12 * * *" ] +crons = ["0 */6 * * *","0 */11 * * *" ] # # Durable Object binding - For more information: https://developers.cloudflare.com/workers/runtime-apis/durable-objects # [[durable_objects]] From c4745598a81fba606498cf7fdb140a491084dfd8 Mon Sep 17 00:00:00 2001 From: Ajeyakrishna <98796547+Ajeyakrishna-k@users.noreply.github.com> Date: Mon, 18 Dec 2023 20:09:38 +0530 Subject: [PATCH 45/45] Update token expiry time (#47) * chore: update token expiry time * fix: staging missed update role id --- src/constants/commons.ts | 2 +- src/handlers/scheduledEventHandler.ts | 1 + src/services/rdsBackendService.ts | 2 +- src/tests/services/rdsBackendService.test.ts | 2 +- src/utils/generateJwt.ts | 4 ++-- 5 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/constants/commons.ts b/src/constants/commons.ts index 77deb0f..5814c54 100644 --- a/src/constants/commons.ts +++ b/src/constants/commons.ts @@ -1,3 +1,3 @@ export const MISSED_UPDATES_PROD_ROLE_ID = '1183553844811153458'; -export const MISSED_UPDATES_STAGING_ROLE_ID = '1183553844811153458'; +export const MISSED_UPDATES_STAGING_ROLE_ID = '1184201657404362772'; export const MISSED_UPDATES_DEVELOPMENT_ROLE_ID = '1181214205081296896'; diff --git a/src/handlers/scheduledEventHandler.ts b/src/handlers/scheduledEventHandler.ts index e5d81c8..256cd26 100644 --- a/src/handlers/scheduledEventHandler.ts +++ b/src/handlers/scheduledEventHandler.ts @@ -89,6 +89,7 @@ export const addMissedUpdatesRole = async (env: env) => { } cursor = missedUpdatesUsers?.cursor; } + // add logs for the results https://github.com/Real-Dev-Squad/website-backend/issues/1784 } catch (err) { console.error('Error while adding missed updates roles'); } diff --git a/src/services/rdsBackendService.ts b/src/services/rdsBackendService.ts index 695b0f8..64e1545 100644 --- a/src/services/rdsBackendService.ts +++ b/src/services/rdsBackendService.ts @@ -26,7 +26,7 @@ export const getMissedUpdatesUsers = async (env: env, cursor: string | undefined const responseData: DiscordUsersResponse = await response.json(); return responseData?.data; } catch (error) { - console.error('Error occurrent while fetching discord user details'); + console.error('Error occurred while fetching discord user details'); throw error; } }; diff --git a/src/tests/services/rdsBackendService.test.ts b/src/tests/services/rdsBackendService.test.ts index cbf1a28..2daa3cf 100644 --- a/src/tests/services/rdsBackendService.test.ts +++ b/src/tests/services/rdsBackendService.test.ts @@ -62,7 +62,7 @@ describe('rdsBackendService', () => { const consoleSpy = jest.spyOn(console, 'error'); jest.spyOn(global, 'fetch').mockRejectedValueOnce(new Error('Error occurred')); await expect(getMissedUpdatesUsers({}, cursor)).rejects.toThrow('Error occurred'); - expect(consoleSpy).toHaveBeenCalledWith('Error occurrent while fetching discord user details'); + expect(consoleSpy).toHaveBeenCalledWith('Error occurred while fetching discord user details'); }); }); }); diff --git a/src/utils/generateJwt.ts b/src/utils/generateJwt.ts index b086ae0..dd1c203 100644 --- a/src/utils/generateJwt.ts +++ b/src/utils/generateJwt.ts @@ -7,7 +7,7 @@ export const generateJwt = async (env: env) => { const authToken = await jwt.sign( { name: 'Cron Job Handler', - exp: Math.floor(Date.now() / 1000) + 2, + exp: Math.floor(Date.now() / 1000) + 60, }, env.CRON_JOB_PRIVATE_KEY, { algorithm: 'RS256' }, @@ -23,7 +23,7 @@ export const generateDiscordBotJwt = async (env: env) => { try { const authToken = await jwt.sign( { - exp: Math.floor(Date.now() / 1000) + 2, + exp: Math.floor(Date.now() / 1000) + 60, }, env.DISCORD_BOT_PRIVATE_KEY, { algorithm: 'RS256' },