The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
improve tags & webhook checks for bulk link creation
Steven Tey3c67205cff2f
diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.tsindex fec5a263d8..4cbd33a53b 100644--- a/apps/web/app/api/links/bulk/route.ts+++ b/apps/web/app/api/links/bulk/route.ts@@ -1,5 +1,11 @@import { DubApiError, exceededLimitError } from "@/lib/api/errors";-import { bulkCreateLinks, combineTagIds, processLink } from "@/lib/api/links";+import {+ bulkCreateLinks,+ checkIfLinksHaveTags,+ checkIfLinksHaveWebhooks,+ combineTagIds,+ processLink,+} from "@/lib/api/links";import { bulkDeleteLinks } from "@/lib/api/links/bulk-delete-links";import { bulkUpdateLinks } from "@/lib/api/links/bulk-update-links";import { throwIfLinksUsageExceeded } from "@/lib/api/links/usage-checks";@@ -86,49 +92,99 @@ export const POST = withWorkspace(code,}));- // filter out tags that don't belong to the workspace- const workspaceTags = await prisma.tag.findMany({- where: {- projectId: workspace.id,- },- select: {- id: true,- name: true,- },- });- const workspaceTagIds = workspaceTags.map(({ id }) => id);- const workspaceTagNames = workspaceTags.map(({ name }) => name);- validLinks.forEach((link, index) => {- const combinedTagIds =- combineTagIds({- tagId: link.tagId,- tagIds: link.tagIds,- }) ?? [];- const invalidTagIds = combinedTagIds.filter(- (id) => !workspaceTagIds.includes(id),- );- if (invalidTagIds.length > 0) {- // remove link from validLinks and add error to errorLinks- validLinks = validLinks.filter((_, i) => i !== index);- errorLinks.push({- error: `Invalid tagIds detected: ${invalidTagIds.join(", ")}`,- code: "unprocessable_entity",- link,- });- }+ if (checkIfLinksHaveTags(validLinks)) {+ // filter out tags that don't belong to the workspace+ const tagIds = validLinks+ .map((link) =>+ combineTagIds({ tagId: link.tagId, tagIds: link.tagIds }),+ )+ .flat()+ .filter(Boolean) as string[];+ const tagNames = validLinks+ .map((link) => link.tagNames)+ .flat()+ .filter(Boolean) as string[];++ const workspaceTags = await prisma.tag.findMany({+ where: {+ projectId: workspace.id,+ ...(tagIds.length > 0 ? { id: { in: tagIds } } : {}),+ ...(tagNames.length > 0 ? { name: { in: tagNames } } : {}),+ },+ select: {+ id: true,+ name: true,+ },+ });+ const workspaceTagIds = workspaceTags.map(({ id }) => id);+ const workspaceTagNames = workspaceTags.map(({ name }) => name);+ validLinks.forEach((link, index) => {+ const combinedTagIds =+ combineTagIds({+ tagId: link.tagId,+ tagIds: link.tagIds,+ }) ?? [];+ const invalidTagIds = combinedTagIds.filter(+ (id) => !workspaceTagIds.includes(id),+ );+ if (invalidTagIds.length > 0) {+ // remove link from validLinks and add error to errorLinks+ validLinks = validLinks.filter((_, i) => i !== index);+ errorLinks.push({+ error: `Invalid tagIds detected: ${invalidTagIds.join(", ")}`,+ code: "unprocessable_entity",+ link,+ });+ }- const invalidTagNames = link.tagNames?.filter(- (name) => !workspaceTagNames.includes(name),- );- if (invalidTagNames?.length) {- validLinks = validLinks.filter((_, i) => i !== index);- errorLinks.push({- error: `Invalid tagNames detected: ${invalidTagNames.join(", ")}`,- code: "unprocessable_entity",- link,+ const invalidTagNames = link.tagNames?.filter(+ (name) => !workspaceTagNames.includes(name),+ );+ if (invalidTagNames?.length) {+ validLinks = validLinks.filter((_, i) => i !== index);+ errorLinks.push({+ error: `Invalid tagNames detected: ${invalidTagNames.join(", ")}`,+ code: "unprocessable_entity",+ link,+ });+ }+ });+ }++ if (checkIfLinksHaveWebhooks(validLinks)) {+ if (workspace.plan === "free" || workspace.plan === "pro") {+ throw new DubApiError({+ code: "forbidden",+ message:+ "You can only use webhooks on a Business plan and above. Upgrade to Business to use this feature.",});}- });++ const webhookIds = validLinks+ .map((link) => link.webhookIds)+ .flat()+ .filter((id): id is string => id !== null);++ const webhooks = await prisma.webhook.findMany({+ where: { projectId: workspace.id, id: { in: webhookIds } },+ });++ const workspaceWebhookIds = webhooks.map(({ id }) => id);++ validLinks.forEach((link, index) => {+ const invalidWebhookIds = link.webhookIds?.filter(+ (id) => !workspaceWebhookIds.includes(id),+ );+ if (invalidWebhookIds && invalidWebhookIds.length > 0) {+ validLinks = validLinks.filter((_, i) => i !== index);+ errorLinks.push({+ error: `Invalid webhookIds detected: ${invalidWebhookIds.join(", ")}`,+ code: "unprocessable_entity",+ link,+ });+ }+ });+ }const validLinksResponse =validLinks.length > 0 ? await bulkCreateLinks({ links: validLinks }) : [];diff --git a/apps/web/lib/api/links/bulk-create-links.ts b/apps/web/lib/api/links/bulk-create-links.tsindex a5c3c0881e..226c962bbe 100644--- a/apps/web/lib/api/links/bulk-create-links.ts+++ b/apps/web/lib/api/links/bulk-create-links.ts@@ -9,7 +9,13 @@ import {import { waitUntil } from "@vercel/functions";import { propagateBulkLinkChanges } from "./propagate-bulk-link-changes";import { updateLinksUsage } from "./update-links-usage";-import { combineTagIds, LinkWithTags, transformLink } from "./utils";+import {+ checkIfLinksHaveTags,+ checkIfLinksHaveWebhooks,+ combineTagIds,+ LinkWithTags,+ transformLink,+} from "./utils";export async function bulkCreateLinks({links,@@ -18,19 +24,18 @@ export async function bulkCreateLinks({}) {if (links.length === 0) return [];- const hasTags = links.some(- (link) => link.tagNames?.length || link.tagIds?.length || link.tagId,- );+ const hasTags = checkIfLinksHaveTags(links);+ const hasWebhooks = checkIfLinksHaveWebhooks(links);let createdLinks: LinkWithTags[] = [];- if (hasTags) {+ if (hasTags || hasWebhooks) {// create links via Promise.all (because createMany doesn't return the created links)// @see https://github.com/prisma/prisma/issues/8131#issuecomment-997667070// there is createManyAndReturn but it's not available for MySQL :(// @see https://www.prisma.io/docs/orm/reference/prisma-client-reference#createmanyandreturncreatedLinks = await Promise.all(- links.map(({ tagId, tagIds, tagNames, ...link }) => {+ links.map(({ tagId, tagIds, tagNames, webhookIds, ...link }) => {const shortLink = linkConstructor({domain: link.domain,key: link.key,@@ -82,6 +87,17 @@ export async function bulkCreateLinks({},},}),++ ...(webhookIds &&+ webhookIds.length > 0 && {+ webhooks: {+ createMany: {+ data: webhookIds.map((webhookId) => ({+ webhookId,+ })),+ },+ },+ }),},include: {tags: {@@ -95,6 +111,7 @@ export async function bulkCreateLinks({},},},+ webhooks: hasWebhooks,},});}),diff --git a/apps/web/lib/api/links/process-link.ts b/apps/web/lib/api/links/process-link.tsindex c0eec23c34..2a3a52ad63 100644--- a/apps/web/lib/api/links/process-link.ts+++ b/apps/web/lib/api/links/process-link.ts@@ -357,51 +357,88 @@ export async function processLink<T extends Record<string, any>>({// only perform tag validity checks if:// - not bulk creation (we do that check separately in the route itself)// - tagIds are present- } else if (tagIds && tagIds.length > 0) {- const tags = await prisma.tag.findMany({- select: {- id: true,- },- where: { projectId: workspace?.id, id: { in: tagIds } },- });+ } else {+ // Tag validity checks+ if (tagIds && tagIds.length > 0) {+ const tags = await prisma.tag.findMany({+ select: {+ id: true,+ },+ where: { projectId: workspace?.id, id: { in: tagIds } },+ });- if (tags.length !== tagIds.length) {- return {- link: payload,- error:- "Invalid tagIds detected: " +- tagIds- .filter(- (tagId) => tags.find(({ id }) => tagId === id) === undefined,- )- .join(", "),- code: "unprocessable_entity",- };+ if (tags.length !== tagIds.length) {+ return {+ link: payload,+ error:+ "Invalid tagIds detected: " ++ tagIds+ .filter(+ (tagId) => tags.find(({ id }) => tagId === id) === undefined,+ )+ .join(", "),+ code: "unprocessable_entity",+ };+ }+ } else if (tagNames && tagNames.length > 0) {+ const tags = await prisma.tag.findMany({+ select: {+ name: true,+ },+ where: {+ projectId: workspace?.id,+ name: { in: tagNames },+ },+ });++ if (tags.length !== tagNames.length) {+ return {+ link: payload,+ error:+ "Invalid tagNames detected: " ++ tagNames+ .filter(+ (tagName) =>+ tags.find(({ name }) => tagName === name) === undefined,+ )+ .join(", "),+ code: "unprocessable_entity",+ };+ }}- } else if (tagNames && tagNames.length > 0) {- const tags = await prisma.tag.findMany({- select: {- name: true,- },- where: {- projectId: workspace?.id,- name: { in: tagNames },- },- });- if (tags.length !== tagNames.length) {- return {- link: payload,- error:- "Invalid tagNames detected: " +- tagNames- .filter(- (tagName) =>- tags.find(({ name }) => tagName === name) === undefined,- )- .join(", "),- code: "unprocessable_entity",- };+ // Webhook validity checks+ if (webhookIds && webhookIds.length > 0) {+ if (!workspace || workspace.plan === "free" || workspace.plan === "pro") {+ return {+ link: payload,+ error:+ "You can only use webhooks on a Business plan and above. Upgrade to Business to use this feature.",+ code: "forbidden",+ };+ }++ webhookIds = [...new Set(webhookIds)];++ const webhooks = await prisma.webhook.findMany({+ select: {+ id: true,+ },+ where: { projectId: workspace?.id, id: { in: webhookIds } },+ });++ if (webhooks.length !== webhookIds.length) {+ const invalidWebhookIds = webhookIds.filter(+ (webhookId) =>+ webhooks.find(({ id }) => webhookId === id) === undefined,+ );++ return {+ link: payload,+ error: "Invalid webhookIds detected: " + invalidWebhookIds.join(", "),+ code: "unprocessable_entity",+ };+ }}}@@ -437,31 +474,6 @@ export async function processLink<T extends Record<string, any>>({}}- // Validate the webhooks- if (webhookIds && webhookIds.length > 0) {- webhookIds = [...new Set(webhookIds)];-- const webhooks = await prisma.webhook.findMany({- select: {- id: true,- },- where: { projectId: workspace?.id, id: { in: webhookIds } },- });-- if (webhooks.length !== webhookIds.length) {- const invalidWebhookIds = webhookIds.filter(- (webhookId) =>- webhooks.find(({ id }) => webhookId === id) === undefined,- );-- return {- link: payload,- error: "Invalid webhookIds detected: " + invalidWebhookIds.join(", "),- code: "unprocessable_entity",- };- }- }-// remove polyfill attributes from payloaddelete payload["shortLink"];delete payload["qrCode"];diff --git a/apps/web/lib/api/links/utils/check-if-links-have-tags.ts b/apps/web/lib/api/links/utils/check-if-links-have-tags.tsnew file mode 100644index 0000000000..e66fc6c034--- /dev/null+++ b/apps/web/lib/api/links/utils/check-if-links-have-tags.ts@@ -0,0 +1,6 @@+import { ProcessedLinkProps } from "../../../types";++export const checkIfLinksHaveTags = (links: ProcessedLinkProps[]) =>+ links.some(+ (link) => link.tagNames?.length || link.tagIds?.length || link.tagId,+ );diff --git a/apps/web/lib/api/links/utils/check-if-links-have-webhooks.ts b/apps/web/lib/api/links/utils/check-if-links-have-webhooks.tsnew file mode 100644index 0000000000..90dcab6807--- /dev/null+++ b/apps/web/lib/api/links/utils/check-if-links-have-webhooks.ts@@ -0,0 +1,4 @@+import { ProcessedLinkProps } from "../../../types";++export const checkIfLinksHaveWebhooks = (links: ProcessedLinkProps[]) =>+ links.some((link) => link.webhookIds?.length);diff --git a/apps/web/lib/api/links/utils/index.ts b/apps/web/lib/api/links/utils/index.tsindex 91e60a6e11..ea2235f56f 100644--- a/apps/web/lib/api/links/utils/index.ts+++ b/apps/web/lib/api/links/utils/index.ts@@ -1,3 +1,5 @@+export * from "./check-if-links-have-tags";+export * from "./check-if-links-have-webhooks";export * from "./combine-tag-ids";export * from "./key-checks";export * from "./process-key";