Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: OOO Nickname Update Job #11

Merged
merged 19 commits into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
bharati-21 marked this conversation as resolved.
Show resolved Hide resolved
}
return { baseUrl };
};
4 changes: 4 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const KEY_NAME = 'DISCORD_NICKNAME_CHANGED';
const NAMESPACE_NAME = 'CRON_JOBS_TIMESTAMPS';
bharati-21 marked this conversation as resolved.
Show resolved Hide resolved

export { KEY_NAME, NAMESPACE_NAME };
46 changes: 46 additions & 0 deletions src/handlers/scheduledEventHandler.ts
Original file line number Diff line number Diff line change
@@ -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;
prakashchoudhary07 marked this conversation as resolved.
Show resolved Hide resolved
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');
prakashchoudhary07 marked this conversation as resolved.
Show resolved Hide resolved
throw err;
}

const url = handleConfig(env);
prakashchoudhary07 marked this conversation as resolved.
Show resolved Hide resolved
let token;
try {
token = await generateJwt(env);
} catch (err) {
console.log(`Error while generating JWT token: ${err}`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re: console.error

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the log both console.log and console.error appears as a generic log. But I've changed it to console.error anyway now.

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,
bharati-21 marked this conversation as resolved.
Show resolved Hide resolved
}),
});
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;
}
13 changes: 11 additions & 2 deletions src/worker.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
import { ping } from './handlers/scheduledEventHandler';
import { callDiscordNicknameBatchUpdate, ping } from './handlers/scheduledEventHandler';
import { env } from './types/global.types';

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) {
ctx.waitUntil(ping(env));
switch (req.cron) {
case '0 */4 * * *':
ctx.waitUntil(ping(env));
break;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does this notify us when backend is down?

case '0 */6 * * *':
await callDiscordNicknameBatchUpdate(env);
prakashchoudhary07 marked this conversation as resolved.
Show resolved Hide resolved
break;
bharati-21 marked this conversation as resolved.
Show resolved Hide resolved
default:
console.log('Unknown Trigger Value!');
}
prakashchoudhary07 marked this conversation as resolved.
Show resolved Hide resolved
},
bharati-21 marked this conversation as resolved.
Show resolved Hide resolved
// 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
Expand Down
18 changes: 12 additions & 6 deletions wrangler.toml
Original file line number Diff line number Diff line change
@@ -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" }
bharati-21 marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's this id?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are public IDs to identify namespaces bound to a single account.

]

# [env.production]
# the BINDING_NAME must be CRON_JOBS_TIMESTAMPS to override in the production env
# kv_namespaces = [
# { binding = "<BINDING_NAME>", id = "<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]]
Expand Down
Loading