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.

Support filtering by tagId array

Tim Wilson1a6e6b8b7af6
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.ts
index 390290e0f3..07c0993e29 100644
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@ -7,11 +7,10 @@ import { NextResponse } from "next/server";
// GET /api/links – get all user links
export const GET = withAuth(async ({ headers, searchParams, project }) => {
- const { domain, tagId, tagIds, search, sort, page, userId, showArchived } =
+ const { domain, tagId, search, sort, page, userId, showArchived } =
searchParams as {
domain?: string;
- tagId?: string;
- tagIds?: string[];
+ tagId?: string | string[];
search?: string;
sort?: "createdAt" | "clicks" | "lastClicked";
page?: string;
@@ -23,7 +22,6 @@ export const GET = withAuth(async ({ headers, searchParams, project }) => {
projectId: project.id,
domain,
tagId,
- tagIds,
search,
sort,
page,
diff --git a/apps/web/app/api/route.ts b/apps/web/app/api/route.ts
index 30e0b7ff00..648daf14f4 100644
--- a/apps/web/app/api/route.ts
+++ b/apps/web/app/api/route.ts
@@ -62,25 +62,21 @@ export function GET(): NextResponse<OpenAPIV3.Document> {
},
{
name: "tagId",
- description: "The tag ID to filter the links by.",
+ description: "The tag ID(s) to filter the links by.",
in: "query",
required: false,
- deprecated: true,
schema: {
- description: "The tag ID to filter the links by.",
- type: "string",
- },
- },
- {
- name: "tagIds",
- description: "The tag IDs to filter the links by.",
- in: "query",
- required: false,
- schema: {
- type: "array",
- items: {
- type: "string",
- },
+ oneOf: [
+ {
+ type: "string",
+ },
+ {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ ],
},
},
{
diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.ts
index bd1600acc7..e38797cd1f 100644
--- a/apps/web/lib/api/links.ts
+++ b/apps/web/lib/api/links.ts
@@ -10,6 +10,7 @@ import {
DEFAULT_REDIRECTS,
DUB_DOMAINS,
SHORT_DOMAIN,
+ ensureArray,
getDomainWithoutWWW,
getParamsFromURL,
getUrlFromString,
@@ -33,7 +34,6 @@ export async function getLinksForProject({
projectId,
domain,
tagId,
- tagIds,
search,
sort = "createdAt",
page,
@@ -42,15 +42,14 @@ export async function getLinksForProject({
}: {
projectId: string;
domain?: string;
- tagId?: string;
- tagIds?: string[];
+ tagId?: string | string[];
search?: string;
sort?: "createdAt" | "clicks" | "lastClicked"; // descending for all
page?: string;
userId?: string | null;
showArchived?: boolean;
}): Promise<LinkProps[]> {
- const combinedTagIds = combineTagIds({ tagId, tagIds });
+ const tagIds = ensureArray(tagId ?? []);
const links = await prisma.link.findMany({
where: {
@@ -67,8 +66,8 @@ export async function getLinksForProject({
},
],
}),
- ...(combinedTagIds?.length && {
- tags: { some: { tagId: { in: combinedTagIds } } },
+ ...(tagIds?.length && {
+ tags: { some: { tagId: { in: tagIds } } },
}),
...(userId && { userId }),
},
@@ -106,17 +105,15 @@ export async function getLinksCount({
projectId: string;
userId?: string | null;
}) {
- let { groupBy, search, domain, tagId, tagIds, showArchived } =
- searchParams as {
- groupBy?: "domain" | "tagId";
- search?: string;
- domain?: string;
- tagId?: string;
- tagIds?: string[];
- showArchived?: boolean;
- };
+ let { groupBy, search, domain, tagId, showArchived } = searchParams as {
+ groupBy?: "domain" | "tagId";
+ search?: string;
+ domain?: string;
+ tagId?: string;
+ showArchived?: boolean;
+ };
- const combinedTagIds = combineTagIds({ tagId, tagIds });
+ const tagIds = ensureArray(tagId ?? []);
const linksWhere = {
archived: showArchived ? undefined : false,
@@ -166,11 +163,11 @@ export async function getLinksCount({
const where = {
projectId,
...linksWhere,
- ...(combinedTagIds?.length && {
+ ...(tagIds?.length && {
tags: {
some: {
id: {
- in: combinedTagIds,
+ in: tagIds,
},
},
},
diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.ts
index da3efab3f7..625d5376e2 100644
--- a/apps/web/lib/auth/index.ts
+++ b/apps/web/lib/auth/index.ts
@@ -48,7 +48,7 @@ interface WithAuthHandler {
}: {
req: Request;
params: Record<string, string>;
- searchParams: Record<string, string>;
+ searchParams: Record<string, string | string[]>;
headers?: Record<string, string>;
session: Session;
project: ProjectProps;
diff --git a/apps/web/ui/links/link-filters.tsx b/apps/web/ui/links/link-filters.tsx
index f204481cab..1057f8f787 100644
--- a/apps/web/ui/links/link-filters.tsx
+++ b/apps/web/ui/links/link-filters.tsx
@@ -263,6 +263,22 @@ const TagsFilter = ({
const [search, setSearch] = useState("");
const [showMore, setShowMore] = useState(false);
+ const selectedTagIds = searchParams?.getAll("tagId");
+
+ const onCheckboxChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ queryParams({
+ set: {
+ tagId: e.target.checked
+ ? [...selectedTagIds, e.target.id]
+ : selectedTagIds.filter((tagId) => tagId !== e.target.id) ?? [],
+ },
+ del: "page",
+ });
+ },
+ [selectedTagIds],
+ );
+
const options = useMemo(() => {
const initialOptions = tags
.map((tag) => ({
@@ -332,16 +348,9 @@ const TagsFilter = ({
<input
id={id}
name={id}
- checked={searchParams?.get("tagId") === id}
- onChange={() => {
- queryParams({
- set: {
- tagId: id,
- },
- del: "page",
- });
- }}
- type="radio"
+ checked={selectedTagIds.includes(id)}
+ onChange={onCheckboxChange}
+ type="checkbox"
className="ml-3 h-4 w-4 cursor-pointer rounded-full border-gray-300 text-black focus:outline-none focus:ring-0"
/>
<label
diff --git a/packages/ui/src/hooks/use-router-stuff.ts b/packages/ui/src/hooks/use-router-stuff.ts
index f2df568f85..b62053c87d 100644
--- a/packages/ui/src/hooks/use-router-stuff.ts
+++ b/packages/ui/src/hooks/use-router-stuff.ts
@@ -29,14 +29,25 @@ export default function useRouterStuff() {
replace,
getNewPath,
}: {
- set?: Record<string, string>;
+ set?: Record<string, string | string[]>;
del?: string | string[];
replace?: boolean;
getNewPath?: boolean;
}) => {
const newParams = new URLSearchParams(searchParams);
if (set) {
- Object.entries(set).forEach(([k, v]) => newParams.set(k, v));
+ const entries = Object.entries(set);
+ entries.forEach(([k, v]) => {
+ if (Array.isArray(v)) {
+ // Clear any old values
+ newParams.delete(k);
+
+ // Append each array item
+ v.forEach((vv) => newParams.append(k, vv));
+ } else {
+ newParams.set(k, v);
+ }
+ });
}
if (del) {
if (Array.isArray(del)) {
diff --git a/packages/utils/src/functions/ensure-array.ts b/packages/utils/src/functions/ensure-array.ts
new file mode 100644
index 0000000000..ddcab0a31a
--- /dev/null
+++ b/packages/utils/src/functions/ensure-array.ts
@@ -0,0 +1,6 @@
+/**
+ * Wraps the provided item in an array if it isn't already one
+ */
+export function ensureArray<T>(itemOrArray: T | T[]) {
+ return Array.isArray(itemOrArray) ? itemOrArray : [itemOrArray];
+}
diff --git a/packages/utils/src/functions/index.ts b/packages/utils/src/functions/index.ts
index a866b92bff..30cedb7519 100644
--- a/packages/utils/src/functions/index.ts
+++ b/packages/utils/src/functions/index.ts
@@ -5,6 +5,7 @@ export * from "./construct-metadata";
export * from "./datetime";
export * from "./deep-equal";
export * from "./domains";
+export * from "./ensure-array";
export * from "./fetch-with-timeout";
export * from "./fetcher";
export * from "./hash";
diff --git a/packages/utils/src/functions/urls.ts b/packages/utils/src/functions/urls.ts
index 7e00dc11e2..8271eb2008 100644
--- a/packages/utils/src/functions/urls.ts
+++ b/packages/utils/src/functions/urls.ts
@@ -18,15 +18,19 @@ export const getUrlFromString = (str: string) => {
}
};
+/**
+ * Gets search params from a URL, supporting multiple values for a single key as an array value
+ */
export const getSearchParams = (url: string) => {
- // Create a params object
- let params = {} as Record<string, string>;
-
- new URL(url).searchParams.forEach(function (val, key) {
- params[key] = val;
- });
-
- return params;
+ return [...new URL(url).searchParams.entries()].reduce(
+ (params, [k, v]) =>
+ k in params
+ ? // Key already exists; append
+ { ...params, [k]: [v].concat(params[k]) }
+ : // Key does not exist; set
+ { ...params, [k]: v },
+ {} as Record<string, string | string[]>,
+ );
};
export const getParamsFromURL = (url: string) => {