Added documentation, info and debug logs, and moved mutation key check to a reusable function. #4

Merged
werewolfkid merged 1 commits from debug-resolver into main 2026-05-09 19:37:45 -04:00
2 changed files with 156 additions and 54 deletions
+155 -54
View File
@@ -4,13 +4,29 @@ import { BigIntResolver } from "graphql-scalars";
const envMutationKey = process.env.MUTATION_KEY || ""; const envMutationKey = process.env.MUTATION_KEY || "";
const env = process.env.NODE_ENV || "development"; const env = process.env.NODE_ENV || "development";
/**
* Check if a date provided is the current date.
* @param date the date to check.
* @returns boolean.
*/
const isDailyStatToday = (date: string): boolean => { const isDailyStatToday = (date: string): boolean => {
// Create a new date object and set the time to 00:00:00:00
const today = new Date().setHours(0, 0, 0, 0); const today = new Date().setHours(0, 0, 0, 0);
// Create a new date object using the argument date and set the time to 00:00:00:00
const dailyStatCreated = new Date(date).setHours(0, 0, 0, 0); const dailyStatCreated = new Date(date).setHours(0, 0, 0, 0);
return today == dailyStatCreated; console.info(
`[DEBUG]: today's date: ${new Date(today).toDateString()}; document creation date: ${new Date(dailyStatCreated).toDateString()}`
);
// return the logic check of the two dates.
return today === dailyStatCreated;
}; };
/**
* Fetches the latest DailyStats document form the database.
* @returns DailyStat object
*/
const getLatestDailyStat = async () => { const getLatestDailyStat = async () => {
return await prisma.dailyStats.findFirst({ return await prisma.dailyStats.findFirst({
orderBy: { orderBy: {
@@ -19,6 +35,44 @@ const getLatestDailyStat = async () => {
}); });
}; };
/**
* Checks if a provided key is valid.
* @param providedKey @type {string} the key provided by the request.
* @returns boolean
*/
const mutationKeyCheck = (providedKey?: string): boolean => {
let flag = false;
if (envMutationKey.length === 0) {
console.info(
"[INFO] MUTATION KEY CHECK: FAILED - environment key not set."
);
return flag;
}
if (providedKey === undefined || providedKey.length === 0) {
console.info(
"[INFO] MUTATION KEY CHECK: FAILED - no mutation key provided."
);
return flag;
}
// If provided mutation key is invalid.
if (providedKey !== envMutationKey) {
console.info(
"[INFO] MUTATION KEY CHECK: FAILED - mutation key check has failed."
);
return flag;
}
// If provided key is valid
if (providedKey === envMutationKey) {
return true;
}
return flag;
};
// Prisma // Prisma
export const resolvers = { export const resolvers = {
// scalars // scalars
@@ -40,7 +94,7 @@ export const resolvers = {
if (!startDate || !endDate) { if (!startDate || !endDate) {
console.info( console.info(
"GET STATS RANGE: REFUSED - one or both dates not provided." "[INFO] GET STATS RANGE: REFUSED - one or both dates not provided."
); );
return null; return null;
} }
@@ -84,15 +138,9 @@ export const resolvers = {
// If env is not development check for the mutation key. // If env is not development check for the mutation key.
if (env !== "development") { if (env !== "development") {
// If mutation key was not provided.
if (!mutationKey) {
console.info("INIT: REFUSED - no mutation key was provided.");
return null;
}
// If provided mutation key is invalid. // If provided mutation key is invalid.
if (mutationKey !== envMutationKey) { if (!mutationKeyCheck(mutationKey)) {
console.info("INIT: REFUSED - mutation key provided was incorrect."); console.info("[INFO] INIT: REFUSED - mutation key check has failed.");
return null; return null;
} }
} }
@@ -104,20 +152,20 @@ export const resolvers = {
// Check for daily stats document count. // Check for daily stats document count.
if ((await prisma.dailyStats.count()) === 0) { if ((await prisma.dailyStats.count()) === 0) {
// Make a daily stats document. // Make a daily stats document.
console.info("INIT: created new document"); console.info("[INFO] INIT: created new document");
await prisma.dailyStats.create({ data: { createdAt: createdAtDate } }); await prisma.dailyStats.create({ data: { createdAt: createdAtDate } });
newTablesCount++; newTablesCount++;
} }
// Check for a total stats document. // Check for a total stats document.
if ((await prisma.totalStats.count()) === 0) { if ((await prisma.totalStats.count()) === 0) {
// Make the total stats document. // Make the total stats document.
console.info("INIT: created new document"); console.info("[INFO] INIT: created new document");
await prisma.totalStats.create({ data: { createdAt: createdAtDate } }); await prisma.totalStats.create({ data: { createdAt: createdAtDate } });
newTablesCount++; newTablesCount++;
} }
console.info( console.info(
`INIT: ${newTablesCount} tables have been initialized with data.` `[INFO] INIT: ${newTablesCount} tables have been initialized with data.`
); );
return `${newTablesCount} tables have been initialized with data.`; return `${newTablesCount} tables have been initialized with data.`;
}, },
@@ -130,16 +178,10 @@ export const resolvers = {
// If env is not development check for the mutation key. // If env is not development check for the mutation key.
if (env !== "development") { if (env !== "development") {
// If mutation key was not provided.
if (!mutationKey) {
console.info("CRONJOB: REFUSED - no mutation key was provided.");
return null;
}
// If provided mutation key is invalid. // If provided mutation key is invalid.
if (mutationKey !== envMutationKey) { if (!mutationKeyCheck(mutationKey)) {
console.info( console.info(
"CRONJOB: REFUSED - mutation key provided was incorrect." "[INFO] CRONJOB: REFUSED - mutation key check has failed."
); );
return null; return null;
} }
@@ -151,7 +193,9 @@ export const resolvers = {
if (latestDailyStats !== null) { if (latestDailyStats !== null) {
// Check if the latest document is for today. // Check if the latest document is for today.
if (isDailyStatToday(String(latestDailyStats.createdAt))) { if (isDailyStatToday(String(latestDailyStats.createdAt))) {
console.info("Cron job refused: latest document is current date."); console.info(
"[INFO] Cron job refused: latest document is current date."
);
return null; return null;
} }
} }
@@ -191,7 +235,7 @@ export const resolvers = {
}); });
// Update the total stats document with the new total. // Update the total stats document with the new total.
console.info("CRONJOB: Creating new document."); console.info("[INFO] CRONJOB: Creating new document.");
return await prisma.totalStats.update({ return await prisma.totalStats.update({
where: { where: {
createdAt: totalStats?.createdAt createdAt: totalStats?.createdAt
@@ -216,16 +260,10 @@ export const resolvers = {
// If env is not development check for the mutation key. // If env is not development check for the mutation key.
if (env !== "development") { if (env !== "development") {
// If mutation key was not provided.
if (!mutationKey) {
console.info("ADD GROUP: REFUSED - no mutation key was provided.");
return null;
}
// If provided mutation key is invalid. // If provided mutation key is invalid.
if (mutationKey !== envMutationKey) { if (!mutationKeyCheck(mutationKey)) {
console.info( console.info(
"ADD GROUP: REFUSED - mutation key provided was incorrect." "[INFO] ADD GROUP: REFUSED - mutation key check has failed."
); );
return null; return null;
} }
@@ -244,7 +282,7 @@ export const resolvers = {
existingGroup.username !== groupUsername existingGroup.username !== groupUsername
) { ) {
// Return the document after updating the details. // Return the document after updating the details.
console.info("ADD GROUP: Updated group document."); console.info("[INFO] ADD GROUP: Updated group document.");
return await prisma.groups.update({ return await prisma.groups.update({
where: { where: {
telegramID: existingGroup.telegramID telegramID: existingGroup.telegramID
@@ -258,7 +296,7 @@ export const resolvers = {
} }
// Return document after creating one for the group. // Return document after creating one for the group.
console.info("ADD GROUP: Created new group document."); console.info("[INFO] ADD GROUP: Created new group document.");
return await prisma.groups.create({ return await prisma.groups.create({
data: { data: {
telegramID: groupIDInt, telegramID: groupIDInt,
@@ -275,25 +313,17 @@ export const resolvers = {
// If env is not development check for the mutation key. // If env is not development check for the mutation key.
if (env !== "development") { if (env !== "development") {
// If mutation key was not provided.
if (!mutationKey) {
console.info(
"INCREMENT GROUP: REFUSED - no mutation key was provided."
);
return null;
}
// If provided mutation key is invalid. // If provided mutation key is invalid.
if (mutationKey !== envMutationKey) { if (!mutationKeyCheck(mutationKey)) {
console.info( console.info(
"INCREMENT GROUP: REFUSED - mutation key provided was incorrect." "[INFO] INCREMENT GROUP: REFUSED - mutation key provided was incorrect."
); );
return null; return null;
} }
} }
// Return updated group document after incrementing it. // Return updated group document after incrementing it.
console.info("INCREMENT GROUP: Incremented group document."); console.info("[INFO] INCREMENT GROUP: Incremented group document.");
return await prisma.groups.update({ return await prisma.groups.update({
where: { telegramID: BigInt(groupID) }, where: { telegramID: BigInt(groupID) },
data: { linksDeleted: { increment: linksDeleted } } data: { linksDeleted: { increment: linksDeleted } }
@@ -313,16 +343,10 @@ export const resolvers = {
// If env is not development check for the mutation key. // If env is not development check for the mutation key.
if (env !== "development") { if (env !== "development") {
// If mutation key was not provided.
if (!mutationKey) {
console.info("INCREMENT: REFUSED - no mutation key was provided.");
return null;
}
// If provided mutation key is invalid. // If provided mutation key is invalid.
if (mutationKey !== envMutationKey) { if (!mutationKeyCheck(mutationKey)) {
console.info( console.info(
"INCREMENT: REFUSED - mutation key provided was incorrect." "[INFO] INCREMENT: REFUSED - mutation key check has failed."
); );
return null; return null;
} }
@@ -336,7 +360,7 @@ export const resolvers = {
// Check if the latest document is for today. // Check if the latest document is for today.
if (!isDailyStatToday(String(latestDailyStats.createdAt))) { if (!isDailyStatToday(String(latestDailyStats.createdAt))) {
// Create new daily stats document. // Create new daily stats document.
console.info("INCREMENT: Created new document."); console.info("[INFO] INCREMENT: Created new document.");
const date = new Date().toISOString(); const date = new Date().toISOString();
await prisma.dailyStats await prisma.dailyStats
.create({ data: { createdAt: date } }) .create({ data: { createdAt: date } })
@@ -350,7 +374,9 @@ export const resolvers = {
} }
// Return latest daily stats after incrementing it. // Return latest daily stats after incrementing it.
console.info("INCREMENT: Incremented information on today's document."); console.info(
"[INFO] INCREMENT: Incremented information on today's document."
);
return await prisma.dailyStats.update({ return await prisma.dailyStats.update({
where: { createdAt: latestDailyStats.createdAt }, where: { createdAt: latestDailyStats.createdAt },
data: { data: {
@@ -361,6 +387,81 @@ export const resolvers = {
}); });
} }
} }
// debug: async (
// _parent: unknown,
// data: { mutationKey?: string }
// // _ctx: unknown
// ) => {
// const { mutationKey } = data;
// // If env is not development check for the mutation key.
// if (env !== "development") {
// // If provided mutation key is invalid.
// if (!mutationKeyCheck(mutationKey)) {
// console.info(
// "[DEBUG] CRONJOB: REFUSED - mutation key check has failed."
// );
// return null;
// }
// }
// const latestDailyStats = await getLatestDailyStat();
// // If there is a daily stats documents.S
// if (latestDailyStats !== null) {
// // Check if the latest document is for today.
// if (isDailyStatToday(String(latestDailyStats.createdAt))) {
// console.info("[DEBUG]: latest document is current date.");
// return null;
// }
// }
// // Create new daily stats document.
// // const createdAtDate = new Date().toISOString();
// // await prisma.dailyStats.create({ data: { createdAt: createdAtDate } });
// // Get every daily stats documents.
// // const allStats = await prisma.dailyStats.findMany({});
// // Add all stats into one object.
// // const calculatedStats = allStats.reduce(
// // (acc, curr) => {
// // const links = (acc.linksDeleted += curr.linksDeleted);
// // const commands = (acc.commandResponses += curr.commandResponses);
// // const triggers = (acc.timesTriggered += curr.timesTriggered);
// // return {
// // linksDeleted: links,
// // commandResponses: commands,
// // timesTriggered: triggers
// // };
// // },
// // {
// // linksDeleted: 0,
// // commandResponses: 0,
// // timesTriggered: 0
// // }
// // );
// // Take the total stats document.
// const totalStats = await prisma.totalStats.findFirst({
// orderBy: {
// createdAt: "desc"
// }
// });
// // Update the total stats document with the new total.
// console.info("[DEBUG]: Creating new document.");
// // return await prisma.totalStats.update({
// // where: {
// // createdAt: totalStats?.createdAt
// // },
// // data: {
// // ...calculatedStats
// // }
// // });
// return totalStats;
// }
} }
}; };
+1
View File
@@ -14,6 +14,7 @@ const typeDefs = /* GraphQL */ `
type Mutation { type Mutation {
init(mutationKey: String): String! init(mutationKey: String): String!
cronJob(mutationKey: String): TotalStats cronJob(mutationKey: String): TotalStats
# debug(mutationKey: String): TotalStats
addGroup( addGroup(
groupID: String! groupID: String!
groupName: String! groupName: String!