The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Refactor link usage cron job and remove unused code
Kiran Kf500ab45d769
diff --git a/apps/web/app/api/cron/links/event/route.ts b/apps/web/app/api/cron/links/event/route.tsdeleted file mode 100644index 1f85438d5d..0000000000--- a/apps/web/app/api/cron/links/event/route.ts+++ /dev/null@@ -1,105 +0,0 @@-import { receiver, sendLimitEmail } from "@/lib/cron";-import prisma from "@/lib/prisma";-import { WorkspaceProps } from "@/lib/types";-import { GOOGLE_FAVICON_URL, getApexDomain, log } from "@dub/utils";--export async function POST(req: Request) {- const body = await req.json();- if (process.env.VERCEL === "1") {- const isValid = await receiver.verify({- signature: req.headers.get("Upstash-Signature") || "",- body: JSON.stringify(body),- });- if (!isValid) {- return new Response("Unauthorized", { status: 401 });- }- }-- const { linkId, type } = body as {- linkId: string;- type: "create" | "edit" | "transfer";- };-- const link = await prisma.link.findUnique({- where: {- id: linkId,- },- include: {- tags: true,- },- });-- if (!link) {- return new Response("Link not found", { status: 200 });- }-- // increment links usage and send alert if needed- if (type === "create" && link.projectId) {- const workspace = await prisma.project.update({- where: {- id: link.projectId,- },- data: {- linksUsage: {- increment: 1,- },- },- });-- const percentage = Math.round(- (workspace.linksUsage / workspace.linksLimit) * 100,- );-- // send alert if 80% or 100% of links limit is reached- if (percentage === 80 || percentage === 100) {- // check if the alert has already been sent- const sentNotification = await prisma.sentEmail.findFirst({- where: {- projectId: workspace.id,- type:- percentage === 80- ? "firstLinksLimitEmail"- : "secondLinksLimitEmail",- },- });-- // if not, send the alert- if (!sentNotification) {- const users = await prisma.user.findMany({- where: {- projects: {- some: {- projectId: workspace.id,- },- },- },- select: {- email: true,- },- });-- const emails = users.map(({ email }) => email) as string[];-- await Promise.all([- sendLimitEmail({- emails,- workspace: workspace as unknown as WorkspaceProps,- type:- percentage === 80- ? "firstLinksLimitEmail"- : "secondLinksLimitEmail",- }),- log({- message: `*${- workspace.slug- }* has used ${percentage.toString()}% of its links limit for the month.`,- type: workspace.plan === "free" ? "cron" : "alerts",- mention: workspace.plan !== "free",- }),- ]);- }- }- }-- return new Response("OK", { status: 200 });-}diff --git a/apps/web/app/api/cron/links/usage/route.ts b/apps/web/app/api/cron/links/usage/route.tsindex 8de7b95e41..f51e5feacc 100644--- a/apps/web/app/api/cron/links/usage/route.ts+++ b/apps/web/app/api/cron/links/usage/route.ts@@ -1,6 +1,7 @@-import { verifySignature } from "@/lib/cron";-import { getSearchParams, log } from "@dub/utils";+import { sendLimitEmail, verifySignature } from "@/lib/cron";+import { log } from "@dub/utils";import { NextResponse } from "next/server";+import prisma from "@/lib/prisma";// Cron to update the links usage of each workspace.// Runs once every 5 mins (*/5 * * * *)@@ -11,19 +12,81 @@ export async function GET(req: Request) {return new Response("Unauthorized", { status: 401 });}- // TODO – we need to check if any workspace exceeded 80% of their links usage- // and send a LinkLimitExceeded email- const { skip } = getSearchParams(req.url);-try {- return NextResponse.json({- response: "success",+ const workspaces = await prisma.project.findMany({+ select: {+ id: true,+ name: true,+ slug: true,+ plan: true,+ linksUsage: true,+ linksLimit: true,+ },});++ for (const workspace of workspaces) {+ const percentage = Math.round(+ (workspace.linksUsage / workspace.linksLimit) * 100,+ );++ // Skip if the workspace is not close to the limit+ if (![80, 100].includes(percentage)) {+ continue;+ }++ const sentNotification = await prisma.sentEmail.count({+ where: {+ projectId: workspace.id,+ type:+ percentage === 80+ ? "firstLinksLimitEmail"+ : "secondLinksLimitEmail",+ },+ });++ // Skip if the email has already been sent+ if (sentNotification) {+ continue;+ }++ const users = await prisma.user.findMany({+ where: {+ projects: {+ some: {+ projectId: workspace.id,+ },+ },+ },+ select: {+ email: true,+ },+ });++ const emails = users.map(({ email }) => email) as string[];++ await sendLimitEmail({+ emails,+ workspace,+ type:+ percentage === 80 ? "firstLinksLimitEmail" : "secondLinksLimitEmail",+ });++ log({+ message: `*${+ workspace.slug+ }* has used ${percentage.toString()}% of its links limit for the month.`,+ type: workspace.plan === "free" ? "cron" : "alerts",+ mention: workspace.plan !== "free",+ });+ }++ return new Response("OK");} catch (error) {await log({message: "Usage cron failed. Error: " + error.message,type: "errors",});- return NextResponse.json({ error: error.message });++ return new Response(error.message, { status: 500 });}}diff --git a/apps/web/app/api/cron/usage/utils.ts b/apps/web/app/api/cron/usage/utils.tsindex 246760bd52..2bc3c1a996 100644--- a/apps/web/app/api/cron/usage/utils.ts+++ b/apps/web/app/api/cron/usage/utils.ts@@ -79,7 +79,7 @@ export const updateUsage = async (skip?: number) => {if (!sentFirstUsageLimitEmail) {sendLimitEmail({emails,- workspace: workspace as unknown as WorkspaceProps,+ workspace,type: "firstUsageLimitEmail",});} else {@@ -95,7 +95,7 @@ export const updateUsage = async (skip?: number) => {if (daysSinceFirstEmail >= 3) {sendLimitEmail({emails,- workspace: workspace as unknown as WorkspaceProps,+ workspace,type: "secondUsageLimitEmail",});}diff --git a/apps/web/lib/cron.ts b/apps/web/lib/cron.tsindex 263ae6782a..997fbeefde 100644--- a/apps/web/lib/cron.ts+++ b/apps/web/lib/cron.ts@@ -4,7 +4,7 @@ import { sendEmail } from "emails";import ClicksExceeded from "emails/clicks-exceeded";import LinksLimitAlert from "emails/links-limit";import prisma from "./prisma";-import { WorkspaceProps } from "./types";+import { Project } from "@prisma/client";export const limiter = new Bottleneck({maxConcurrent: 1, // maximum concurrent requests@@ -44,7 +44,7 @@ export const sendLimitEmail = async ({type,}: {emails: string[];- workspace: WorkspaceProps;+ workspace: Pick<Project, "id" | "name" | "linksUsage" | "linksLimit">;type:| "firstUsageLimitEmail"| "secondUsageLimitEmail"diff --git a/apps/web/vercel.json b/apps/web/vercel.jsonindex ec2ded9cd6..64baec4ef8 100644--- a/apps/web/vercel.json+++ b/apps/web/vercel.json@@ -9,7 +9,7 @@"schedule": "0 14 * * *"},{- "path": "/api/links/usage",+ "path": "/api/cron/links/usage","schedule": "*/5 * * * *"}],