Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

add reusable WorkspaceProductCache

Steven Teyf78c76bc4713
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
index baf5f42443..2ba5d8f7b1 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
@@ -3,6 +3,7 @@ import { DubApiError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { validateAllowedHostnames } from "@/lib/api/validate-allowed-hostnames";
import { deleteWorkspace } from "@/lib/api/workspaces/delete-workspace";
+import { workspaceProductCache } from "@/lib/api/workspaces/workspace-product-cache";
import { prefixWorkspaceId } from "@/lib/api/workspaces/workspace-id";
import { withWorkspace } from "@/lib/auth";
import { getFeatureFlags } from "@/lib/edge-config";
@@ -10,7 +11,6 @@ import { jackson } from "@/lib/jackson";
import { prisma } from "@/lib/prisma";
import { mergeSiteVisitTrackingSettings } from "@/lib/sitemaps/site-visit-tracking";
import { storage } from "@/lib/storage";
-import { redis } from "@/lib/upstash";
import {
createWorkspaceSchema,
siteVisitTrackingSettingsPatchSchema,
@@ -230,14 +230,15 @@ export const PATCH = withWorkspace(
},
}),
// refresh the workspace product cache for both workspaces
- redis.del(
- `workspace:product:${updatedWorkspace.slug}`,
- `workspace:product:${workspace.slug}`,
- ),
+ workspaceProductCache.delete({ slug: workspace.slug }),
+ workspaceProductCache.set({
+ slug: updatedWorkspace.slug,
+ product: updatedWorkspace.defaultProduct,
+ }),
]);
} else if (updatedWorkspace.defaultProduct !== workspace.defaultProduct) {
// refresh the workspace product cache for the workspace (if updated)
- await redis.del(`workspace:product:${updatedWorkspace.slug}`);
+ await workspaceProductCache.delete({ slug: updatedWorkspace.slug });
}
waitUntil(
diff --git a/apps/web/lib/actions/partners/create-program.ts b/apps/web/lib/actions/partners/create-program.ts
index b79e7fa23a..02699d8429 100644
--- a/apps/web/lib/actions/partners/create-program.ts
+++ b/apps/web/lib/actions/partners/create-program.ts
@@ -8,7 +8,7 @@ import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { prisma } from "@/lib/prisma";
import { storage } from "@/lib/storage";
import { PlanProps } from "@/lib/types";
-import { redis } from "@/lib/upstash";
+import { workspaceProductCache } from "@/lib/api/workspaces/workspace-product-cache";
import {
DEFAULT_ADDITIONAL_PARTNER_LINKS,
DEFAULT_PARTNER_GROUP,
@@ -287,7 +287,7 @@ export const createProgram = async ({
: []),
// delete the workspace product cache
- redis.del(`workspace:product:${workspace.slug}`),
+ workspaceProductCache.delete({ slug: workspace.slug }),
// record the audit log
recordAuditLog({
diff --git a/apps/web/lib/api/workspaces/workspace-product-cache.ts b/apps/web/lib/api/workspaces/workspace-product-cache.ts
new file mode 100644
index 0000000000..77b3bca073
--- /dev/null
+++ b/apps/web/lib/api/workspaces/workspace-product-cache.ts
@@ -0,0 +1,27 @@
+import { redis } from "@/lib/upstash";
+import { DubProduct } from "@prisma/client";
+
+const CACHE_KEY_PREFIX = "workspace:product";
+const CACHE_EXPIRATION = 60 * 60 * 24 * 30; // 30 days
+
+class WorkspaceProductCache {
+ async get({ slug }: { slug: string }) {
+ return await redis.get<DubProduct>(this._createKey({ slug }));
+ }
+
+ async set({ slug, product }: { slug: string; product: DubProduct }) {
+ return await redis.set(this._createKey({ slug }), product, {
+ ex: CACHE_EXPIRATION,
+ });
+ }
+
+ async delete({ slug }: { slug: string }) {
+ return await redis.del(this._createKey({ slug }));
+ }
+
+ _createKey({ slug }: { slug: string }) {
+ return `${CACHE_KEY_PREFIX}:${slug}`;
+ }
+}
+
+export const workspaceProductCache = new WorkspaceProductCache();
diff --git a/apps/web/lib/middleware/utils/get-workspace-product.ts b/apps/web/lib/middleware/utils/get-workspace-product.ts
index cc5cc92f0a..af76420952 100644
--- a/apps/web/lib/middleware/utils/get-workspace-product.ts
+++ b/apps/web/lib/middleware/utils/get-workspace-product.ts
@@ -1,13 +1,11 @@
+import { workspaceProductCache } from "@/lib/api/workspaces/workspace-product-cache";
import { conn } from "@/lib/planetscale/connection";
import { WorkspaceProps } from "@/lib/types";
-import { redis } from "@/lib/upstash";
import { after } from "next/server";
export const getWorkspaceProduct = async (workspaceSlug: string) => {
try {
- let workspaceProduct = await redis.get<"program" | "links">(
- `workspace:product:${workspaceSlug}`,
- );
+ let workspaceProduct = await workspaceProductCache.get({ slug: workspaceSlug });
if (workspaceProduct) {
return workspaceProduct;
}
@@ -25,8 +23,9 @@ export const getWorkspaceProduct = async (workspaceSlug: string) => {
workspaceProduct = workspace?.defaultProduct ?? "links";
after(async () => {
- await redis.set(`workspace:product:${workspaceSlug}`, workspaceProduct, {
- ex: 60 * 60 * 24 * 30, // cache for 30 days
+ await workspaceProductCache.set({
+ slug: workspaceSlug,
+ product: workspaceProduct,
});
});
diff --git a/apps/web/ui/workspaces/update-default-product.tsx b/apps/web/ui/workspaces/update-default-product.tsx
index 3898910afd..900fd30b3b 100644
--- a/apps/web/ui/workspaces/update-default-product.tsx
+++ b/apps/web/ui/workspaces/update-default-product.tsx
@@ -66,23 +66,25 @@ export default function UpdateDefaultProduct() {
}
setSaving(true);
- const response = await fetch(`/api/workspaces/${id}`, {
- method: "PATCH",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- defaultProduct: selectedProduct,
- }),
- });
+ try {
+ const response = await fetch(`/api/workspaces/${id}`, {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ defaultProduct: selectedProduct,
+ }),
+ });
- if (response.ok) {
- await mutate(`/api/workspaces/${slug}`);
+ if (response.ok) {
+ await mutate(`/api/workspaces/${slug}`);
+ } else {
+ const { error } = await response.json();
+ throw new Error(error.message);
+ }
+ } finally {
setSaving(false);
- } else {
- setSaving(false);
- const { error } = await response.json();
- throw new Error(error.message);
}
}