Skip to content

Commit

Permalink
fix(notify): add complete recursive logic for notify
Browse files Browse the repository at this point in the history
  • Loading branch information
DikDns committed Jul 26, 2024
1 parent a7ad7a3 commit 6d808ef
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 32 deletions.
36 changes: 14 additions & 22 deletions src/app/api/telegram/notify/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,6 @@ export async function POST(request: Request) {
},
{
status: 401,
headers: {
"Cache-Control": "public, s-maxage=1",
"CDN-Cache-Control": "public, s-maxage=60",
"Vercel-CDN-Cache-Control": "public, s-maxage=3600",
},
},
);
}
Expand All @@ -73,25 +68,26 @@ export async function POST(request: Request) {
},
{
status: 200,
headers: {
"Cache-Control": "public, s-maxage=1",
"CDN-Cache-Control": "public, s-maxage=60",
"Vercel-CDN-Cache-Control": "public, s-maxage=3600",
},
},
);
}

// This function behaves like a cron job that runs every 1 second for the limitation of telegram API
async function intervalNotify(body: NotifyBody) {
const baseUrl = "https://blog.himarpl.com";
const title = body.title;
const slug = body.slug;
const name = body.author.name;
const username = body.author.username;

const unnotify = await api.notification.getUnnotify({
slug: body.slug,
slug: `@${username}/${slug}`,
limit: 25,
});

if (unnotify.length === 0) {
const removed = await api.notification.removeNotify({
slug: body.slug,
slug: `@${username}/${slug}`,
});

if (!removed) {
Expand All @@ -101,25 +97,18 @@ async function intervalNotify(body: NotifyBody) {
return;
}

const baseUrl = "https://blog.himarpl.com";
const title = body.title;
const slug = body.slug;

const name = body.author.name;
const username = body.author.username;

for (const notification of unnotify) {
await bot.sendMessage(
notification.chatId,
`📢 *[${title}](${baseUrl}/@${username}/${slug}*\n\n📝 [${name}](${baseUrl}/@${username})`,
`*${notification.firstName?.toUpperCase()}, ADA POSTINGAN BARU!*\n\n[${title?.toUpperCase()}](${baseUrl}/@${username}/${slug})\nditulis oleh [${name}](${baseUrl}/@${username})`,
{
parse_mode: "Markdown",
},
);
}

const notify = await api.notification.notify({
slug: body.slug,
slug: `@${username}/${slug}`,
chatIds: unnotify.map((n) => n.chatId),
});

Expand All @@ -128,7 +117,10 @@ async function intervalNotify(body: NotifyBody) {
}

setTimeout(() => {
waitUntil(intervalNotify(body));
// waitUntil(intervalNotify(body));
intervalNotify(body).catch((err) => {
console.error(err);
});
}, 1000);

return;
Expand Down
29 changes: 19 additions & 10 deletions src/server/api/routers/notification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,15 @@ export const notificationRouter = createTRPCRouter({
notify: publicProcedure
.input(z.object({ slug: z.string(), chatIds: z.array(z.number()).min(1) }))
.mutation(async ({ ctx, input }) => {
const prev = await ctx.db.query.notifications.findMany({
const prevNotif = await ctx.db.query.notifications.findMany({
where: (notification) => inArray(notification.chatId, input.chatIds),
columns: {
chatId: true,
notifying: true,
},
});

if (!prev) {
if (!prevNotif) {
return new TRPCError({
code: "NOT_FOUND",
message: "Notification not found",
Expand All @@ -55,14 +56,20 @@ export const notificationRouter = createTRPCRouter({

// Update many rows at once
const sqlChunks: SQL[] = [];
const ids: number[] = [];

sqlChunks.push(sql`(case`);

for (const currentChatId of input.chatIds) {
const currentNotif = [...prev, input.slug];
for (const currentNotif of prevNotif) {
const currentNotifying = [...currentNotif.notifying, input.slug]
.map((item) => `'${item}'`)
.join(", ");

sqlChunks.push(
sql`when ${notifications.chatId} = ${currentChatId} then ${currentNotif}`,
sql`when ${notifications.chatId} = ${currentNotif.chatId} then ARRAY[${sql.raw(`${currentNotifying}`)}]::text[]`,
);

ids.push(currentNotif.chatId);
}

sqlChunks.push(sql`end)`);
Expand All @@ -72,7 +79,7 @@ export const notificationRouter = createTRPCRouter({
return await ctx.db
.update(notifications)
.set({ notifying: finalSql })
.where(inArray(notifications.chatId, input.chatIds));
.where(inArray(notifications.chatId, ids));
}),
removeNotify: publicProcedure
.input(z.object({ slug: z.string() }))
Expand All @@ -98,11 +105,13 @@ export const notificationRouter = createTRPCRouter({
sqlChunks.push(sql`(case`);

for (const currentNotif of prevNotif) {
const currentNotifying = currentNotif.notifying.filter(
(slug) => slug !== input.slug,
);
const currentNotifying = currentNotif.notifying
.filter((item) => item !== input.slug)
.map((item) => `'${item}'`)
.join(", ");

sqlChunks.push(
sql`when ${notifications.chatId} = ${currentNotif.chatId} then ${currentNotifying}`,
sql`when ${notifications.chatId} = ${currentNotif.chatId} then ARRAY[${sql.raw(`${currentNotifying}`)}]::text[]`,
);
ids.push(currentNotif.chatId);
}
Expand Down

0 comments on commit 6d808ef

Please sign in to comment.