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 tagNames and also use z.infer types

Steven Tey98c70337ca70
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.ts
index 90be9353eb..4b144c6436 100644
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@ -17,6 +17,7 @@ export const GET = withAuth(async ({ headers, searchParams, project }) => {
domain,
tagId,
tagIds,
+ tagNames,
search,
sort,
page,
@@ -30,6 +31,7 @@ export const GET = withAuth(async ({ headers, searchParams, project }) => {
domain,
tagId,
tagIds,
+ tagNames,
search,
sort,
page,
@@ -70,7 +72,7 @@ export const POST = withAuth(
}
const { link, error, code } = await processLink({
- payload: body as LinkWithTagIdsProps,
+ payload: body,
project,
...(session && { userId: session.user.id }),
});
diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.ts
index 0db56a1636..661936d205 100644
--- a/apps/web/lib/api/links.ts
+++ b/apps/web/lib/api/links.ts
@@ -7,6 +7,7 @@ import {
import prisma from "@/lib/prisma";
import { formatRedisLink, redis } from "@/lib/upstash";
import {
+ createLinkBodySchema,
getLinksCountQuerySchema,
getLinksQuerySchema,
} from "@/lib/zod/schemas/links";
@@ -54,6 +55,7 @@ export async function getLinksForProject({
domain,
tagId,
tagIds,
+ tagNames,
search,
sort = "createdAt",
page,
@@ -85,9 +87,23 @@ export async function getLinksForProject({
some: {},
},
}),
- ...(combinedTagIds.length > 0 && {
- tags: { some: { tagId: { in: combinedTagIds } } },
- }),
+ ...(combinedTagIds.length > 0
+ ? {
+ tags: { some: { tagId: { in: combinedTagIds } } },
+ }
+ : tagNames
+ ? {
+ tags: {
+ some: {
+ tag: {
+ name: {
+ in: tagNames,
+ },
+ },
+ },
+ },
+ }
+ : {}),
...(userId && { userId }),
},
include: {
@@ -223,14 +239,19 @@ export async function keyChecks({
}
if (isDubDomain(domain) && process.env.NEXT_PUBLIC_IS_DUB) {
- if (
- domain === SHORT_DOMAIN &&
- (DEFAULT_REDIRECTS[key] || (await isReservedKey(key)))
- ) {
- return {
- error: "Duplicate key: This short link already exists.",
- code: "conflict",
- };
+ if (domain === SHORT_DOMAIN) {
+ if (DEFAULT_REDIRECTS[key] || (await isReservedKey(key))) {
+ return {
+ error: "Duplicate key: This short link already exists.",
+ code: "conflict",
+ };
+ }
+ if (await isBlacklistedKey(key)) {
+ return {
+ error: "Invalid key.",
+ code: "unprocessable_entity",
+ };
+ }
}
if (key.length <= 3 && (!project || project.plan === "free")) {
@@ -274,7 +295,7 @@ export async function processLink({
bulk = false,
skipKeyChecks = false, // only skip when key doesn't change (e.g. when editing a link)
}: {
- payload: LinkWithTagIdsProps;
+ payload: z.infer<typeof createLinkBodySchema>;
project?: ProjectProps;
userId?: string;
bulk?: boolean;
@@ -292,6 +313,7 @@ export async function processLink({
ios,
android,
geo,
+ tagNames,
} = payload;
const tagIds = combineTagIds(payload);
@@ -332,14 +354,6 @@ export async function processLink({
// checks for default short domain
if (domain === SHORT_DOMAIN) {
- const keyBlacklisted = await isBlacklistedKey(key);
- if (keyBlacklisted) {
- return {
- link: payload,
- error: "Invalid key.",
- code: "unprocessable_entity",
- };
- }
const domainBlacklisted = await isBlacklistedDomain(url);
if (domainBlacklisted) {
return {
@@ -419,7 +433,10 @@ export async function processLink({
select: {
id: true,
},
- where: { projectId: project?.id, id: { in: tagIds } },
+ where: {
+ projectId: project?.id,
+ id: { in: tagIds },
+ },
});
if (tags.length !== tagIds.length) {
@@ -435,6 +452,31 @@ export async function processLink({
status: 422,
};
}
+ } else if (tagNames && tagNames.length > 0) {
+ const tags = await prisma.tag.findMany({
+ select: {
+ name: true,
+ },
+ where: {
+ projectId: project?.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(", "),
+ status: 422,
+ };
+ }
}
// custom social media image checks
@@ -529,8 +571,8 @@ export async function addLink(link: LinkWithTagIdsProps) {
data: {
...rest,
key,
- title: truncate(title, 120),
- description: truncate(description, 240),
+ title: truncate(title || "", 120),
+ description: truncate(description || "", 240),
image,
utm_source,
utm_medium,
diff --git a/apps/web/lib/prisma.ts b/apps/web/lib/prisma.ts
index 912e814e7b..10082dc2b2 100644
--- a/apps/web/lib/prisma.ts
+++ b/apps/web/lib/prisma.ts
@@ -4,23 +4,7 @@ declare global {
var prisma: PrismaClient | undefined;
}
-const prisma =
- global.prisma ||
- (new PrismaClient().$extends({
- result: {
- link: {
- tagId: {
- // @ts-ignore https://github.com/prisma/prisma/issues/20091#issuecomment-1824063594
- needs: { tags: true },
- compute(link) {
- if (!link.tags || !link.tags.length) return null;
-
- return link.tags[0].tagId;
- },
- },
- },
- },
- }) as PrismaClient);
+const prisma = global.prisma || new PrismaClient();
if (process.env.NODE_ENV === "development") global.prisma = prisma;
diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.ts
index bdab11d396..fe3df62a7f 100644
--- a/apps/web/lib/zod/schemas/links.ts
+++ b/apps/web/lib/zod/schemas/links.ts
@@ -1,6 +1,7 @@
import z from "@/lib/zod";
import { booleanQuerySchema } from ".";
import { TagSchema } from "./tags";
+import { getRandomKey } from "@/lib/planetscale";
const LinksQuerySchema = {
projectSlug: z
@@ -26,6 +27,13 @@ const LinksQuerySchema = {
.transform((v) => (Array.isArray(v) ? v : v.split(",")))
.optional()
.describe("The tag IDs to filter the links by."),
+ tagNames: z
+ .union([z.string(), z.array(z.string())])
+ .transform((v) => (Array.isArray(v) ? v : v.split(",")))
+ .optional()
+ .describe(
+ "The unique name of the tags assigned to the short link (case insensitive).",
+ ),
search: z
.string()
.optional()
@@ -198,9 +206,17 @@ export const createLinkBodySchema = z.object({
)
.openapi({ deprecated: true }),
tagIds: z
- .array(z.string())
- .nullish()
+ .union([z.string(), z.array(z.string())])
+ .transform((v) => (Array.isArray(v) ? v : v.split(",")))
+ .optional()
.describe("The unique IDs of the tags assigned to the short link."),
+ tagNames: z
+ .union([z.string(), z.array(z.string())])
+ .transform((v) => (Array.isArray(v) ? v : v.split(",")))
+ .optional()
+ .describe(
+ "The unique name of the tags assigned to the short link (case insensitive).",
+ ),
comments: z.string().nullish().describe("The comments for the short link."),
});