The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Merge branch 'main' into bulk-updates
Steven Teya938d5e00510
diff --cc apps/web/app/api/links/bulk/route.tsindex c61af5365b,a8bcd2d898..f27f11e568--- a/apps/web/app/api/links/bulk/route.ts+++ b/apps/web/app/api/links/bulk/route.ts@@@ -131,128 -127,7 +131,131 @@@ export const POST = withWorkspaceheaders,});},+ {+ requiredScopes: ["links.write"],+ },);++// PATCH /api/links/bulk – bulk update up to 100 links with the same data+export const PATCH = withWorkspace(+ async ({ req, workspace, headers }) => {+ const { linkIds, data } = bulkUpdateLinksBodySchema.parse(+ await parseRequestBody(req),+ );++ if (linkIds.length === 0) {+ return NextResponse.json("No links to update", { headers });+ }++ const links = await prisma.link.findMany({+ where: {+ id: { in: linkIds },+ projectId: workspace.id,+ },+ });++ // linkIds that don't exist+ let errorLinks = linkIds+ .filter((id) => links.find((link) => link.id === id) === undefined)+ .map((id) => ({+ error: "Link not found",+ code: "not_found",+ link: { id },+ }));++ let { tagNames, expiresAt } = data;+ const tagIds = combineTagIds(data);+ // tag 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) {+ throw new DubApiError({+ code: "unprocessable_entity",+ message: `Invalid tagIds detected: ${tagIds.filter((tagId) => tags.find(({ id }) => tagId === id) === undefined).join(", ")}`,+ });+ }+ } 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) {+ throw new DubApiError({+ code: "unprocessable_entity",+ message: `Invalid tagNames detected: ${tagNames.filter((tagName) => tags.find(({ name }) => tagName === name) === undefined).join(", ")}`,+ });+ }+ }++ const processedLinks = await Promise.all(+ links.map(async (link) =>+ processLink({+ payload: {+ ...link,+ expiresAt:+ link.expiresAt instanceof Date+ ? link.expiresAt.toISOString()+ : link.expiresAt,+ geo: link.geo as NewLinkProps["geo"],+ ...data,+ },+ workspace,+ userId: link.userId ?? undefined,+ bulk: true,+ skipKeyChecks: true,+ }),+ ),+ );++ const validLinkIds = processedLinks+ .filter(({ error }) => error == null)+ .map(({ link }) => link.id) as string[];++ errorLinks = errorLinks.concat(+ processedLinks+ .filter(({ error }) => error != null)+ .map(({ link, error, code }) => ({+ error: error as string,+ code: code as string,+ link,+ })),+ );++ const response =+ validLinkIds.length > 0+ ? await bulkUpdateLinks({+ linkIds: validLinkIds,+ data: {+ ...data,+ tagIds,+ expiresAt,+ },+ workspaceId: workspace.id,+ })+ : [];++ return NextResponse.json([...response, ...errorLinks], { headers });+ },+ {+ requiredPlan: [+ "pro",+ "business",+ "business plus",+ "business extra",+ "business max",+ "enterprise",+ ],+ },+);diff --cc apps/web/app/api/links/sync/route.tsindex af8f1de0f6,901beae4a0..074c040247--- a/apps/web/app/api/links/sync/route.ts+++ b/apps/web/app/api/links/sync/route.ts@@@ -7,75 -6,76 +7,80 @@@ import { SimpleLinkProps } from "@/lib/import { NextResponse } from "next/server";// POST /api/links/sync – sync user's publicly created links to their accounts- export const POST = withWorkspace(async ({ req, session, workspace }) => {- let links: SimpleLinkProps[] = [];- try {- links = await req.json();- if (!Array.isArray(links)) {- throw new Error("Invalid request body.");+ export const POST = withWorkspace(+ async ({ req, session, workspace }) => {+ let links: SimpleLinkProps[] = [];+ try {+ links = await req.json();+ if (!Array.isArray(links)) {+ throw new Error("Invalid request body.");+ }+ } catch (e) {+ return new Response("Invalid request body.", { status: 400 });}- } catch (e) {- return new Response("Invalid request body.", { status: 400 });- }- const unclaimedLinks = await Promise.all(- links.map(async (link) => {- return await prisma.link.findUnique({- where: {- domain_key: {- domain: link.domain,- key: link.key,+ const unclaimedLinks = await Promise.all(+ links.map(async (link) => {+ return await prisma.link.findUnique({+ where: {+ domain_key: {+ domain: link.domain,+ key: link.key,+ },+ userId: null,},- userId: null,- },- include: {- tags: true,- },- });- }),- ).then((links) => links.filter((link) => link !== null));+ include: {+ tags: true,+ },+ });+ }),+ ).then((links) => links.filter((link) => link !== null));- if (unclaimedLinks.length === 0) {- return new Response("No links created.", { status: 200 });- }+ if (unclaimedLinks.length === 0) {+ return new Response("No links created.", { status: 200 });+ }- if (workspace.linksUsage + unclaimedLinks.length > workspace.linksLimit) {- return new Response(- exceededLimitError({- plan: workspace.plan,- limit: workspace.linksLimit,- type: "links",- }),- { status: 403 },- );- }+ if (workspace.linksUsage + unclaimedLinks.length > workspace.linksLimit) {+ return new Response(+ exceededLimitError({+ plan: workspace.plan,+ limit: workspace.linksLimit,+ type: "links",+ }),+ { status: 403 },+ );+ }- const response = await Promise.allSettled([- prisma.link.updateMany({- where: {- id: {- in: unclaimedLinks.map((link) => link!.id),+ const response = await Promise.allSettled([+ prisma.link.updateMany({+ where: {+ id: {+ in: unclaimedLinks.map((link) => link!.id),+ },},- },- data: {- userId: session.user.id,- projectId: workspace.id,- publicStats: false,- },- }),- propagateBulkLinkChanges(- unclaimedLinks.map((link) => ({- ...link!,- userId: session.user.id,- projectId: workspace.id,- publicStats: false,- })),- ),- updateLinksUsage({- workspaceId: workspace.id,- increment: unclaimedLinks.length,- }),- ]);+ data: {+ userId: session.user.id,+ projectId: workspace.id,+ publicStats: false,+ },+ }),+ propagateBulkLinkChanges(+ unclaimedLinks.map((link) => ({+ ...link!,+ userId: session.user.id,+ projectId: workspace.id,+ publicStats: false,+ })),+ ),++ updateLinksUsage({++ workspaceId: workspace.id,++ increment: unclaimedLinks.length,++ }),+ ]);- return NextResponse.json(response);- });+ return NextResponse.json(response);+ },+ {+ requiredScopes: ["links.write"],+ },+ );