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.

wip

Kiran Kfb139e30aa2c
diff --git a/apps/web/app/api/tokens/embed/route.ts b/apps/web/app/api/tokens/embed/route.ts
index 8a85a30e46..34baab505a 100644
--- a/apps/web/app/api/tokens/embed/route.ts
+++ b/apps/web/app/api/tokens/embed/route.ts
@@ -1,4 +1,6 @@
-import { DubApiError } from "@/lib/api/errors";
+import { DubApiError, ErrorCodes } from "@/lib/api/errors";
+import { createLink, processLink } from "@/lib/api/links";
+import { enrollPartner } from "@/lib/api/partners/enroll-partner";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { embedToken } from "@/lib/embed/embed-token";
@@ -7,46 +9,141 @@ import {
EmbedTokenSchema,
} from "@/lib/zod/schemas/token";
import { prisma } from "@dub/prisma";
+import { ProgramEnrollment } from "@prisma/client";
import { NextResponse } from "next/server";
// POST /api/tokens/embed - create a new embed token for the given partner/tenant
export const POST = withWorkspace(
- async ({ workspace, req }) => {
- const { programId, partnerId, tenantId } = createEmbedTokenSchema.parse(
- await parseRequestBody(req),
- );
-
- if (!partnerId && !tenantId) {
- throw new DubApiError({
- message: "Partner ID or tenant ID is required",
- code: "bad_request",
+ async ({ workspace, req, session }) => {
+ const data = createEmbedTokenSchema.parse(await parseRequestBody(req));
+
+ const { programId } = data;
+
+ // if (!("partnerId" in data) && !("tenantId" in data)) {
+ // throw new DubApiError({
+ // message: "Partner ID or tenant ID is required.",
+ // code: "bad_request",
+ // });
+ // }
+
+ let programEnrollment: ProgramEnrollment | null = null;
+
+ if ("partnerId" in data || "tenantId" in data) {
+ programEnrollment = await prisma.programEnrollment.findUnique({
+ where:
+ "tenantId" in data
+ ? { tenantId_programId: { tenantId: data.tenantId, programId } }
+ : { partnerId_programId: { partnerId: data.partnerId, programId } },
+ include: {
+ program: true,
+ },
});
}
- const programEnrollment = await prisma.programEnrollment.findUnique({
- where: tenantId
- ? { tenantId_programId: { tenantId, programId } }
- : { partnerId_programId: { partnerId: partnerId!, programId } },
- include: {
- program: true,
- },
- });
+ if (!programEnrollment) {
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ });
+
+ if (program.workspaceId !== workspace.id) {
+ throw new DubApiError({
+ message: `Program with ID ${programId} does not belong to this workspace.`,
+ code: "bad_request",
+ });
+ }
+ }
- if (
- !programEnrollment ||
- programEnrollment.program.workspaceId !== workspace.id
- ) {
- throw new DubApiError({
- message: `Partner with ${
- partnerId ? `ID ${partnerId}` : `tenant ID ${tenantId}`
- } not enrolled in this workspace's program ${programId}.`,
- code: "not_found",
+ if ("partner" in data) {
+ const existingPartner = await prisma.partner.findUnique({
+ where: {
+ email: data.partner.email,
+ },
});
+
+ if (existingPartner) {
+ programEnrollment = await prisma.programEnrollment.findUnique({
+ where: {
+ partnerId_programId: {
+ partnerId: existingPartner.id,
+ programId,
+ },
+ },
+ });
+
+ if (!programEnrollment) {
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ });
+
+ if (!program.domain || !program.url) {
+ throw new DubApiError({
+ message: "Program must have a domain and url.",
+ code: "bad_request",
+ });
+ }
+
+ const { linkProps, username, tenantId } = data.partner;
+
+ const { link, error, code } = await processLink({
+ workspace,
+ userId: session.user.id,
+ payload: {
+ ...linkProps,
+ domain: program.domain,
+ key: username,
+ url: program.url,
+ programId,
+ tenantId,
+ folderId: program.defaultFolderId,
+ trackConversion: true,
+ },
+ });
+
+ // TODO:
+ // Handle case when the shortlink key is already taken
+
+ if (error != null) {
+ throw new DubApiError({
+ code: code as ErrorCodes,
+ message: error,
+ });
+ }
+
+ const partnerLink = await createLink(link);
+
+ await enrollPartner({
+ program,
+ tenantId,
+ workspace,
+ link: partnerLink,
+ partner: data.partner,
+ });
+ }
+ }
}
+ // if (
+ // !programEnrollment ||
+ // programEnrollment.program.workspaceId !== workspace.id
+ // ) {
+ // throw new DubApiError({
+ // message: `Partner with ${
+ // partnerId ? `ID ${partnerId}` : `tenant ID ${tenantId}`
+ // } not enrolled in this workspace's program ${programId}.`,
+ // code: "not_found",
+ // });
+ // }
+
const response = await embedToken.create({
programId,
- partnerId: programEnrollment.partnerId,
+ ...(programEnrollment && { partnerId: programEnrollment.partnerId }),
+ ...("partner" in data && {
+ partner: data.partner,
+ }),
});
return NextResponse.json(EmbedTokenSchema.parse(response), {
diff --git a/apps/web/lib/embed/embed-token.ts b/apps/web/lib/embed/embed-token.ts
index 231260ca0d..d799db77a7 100644
--- a/apps/web/lib/embed/embed-token.ts
+++ b/apps/web/lib/embed/embed-token.ts
@@ -1,15 +1,18 @@
import { redis } from "@/lib/upstash";
+import { z } from "zod";
import { createId } from "../api/utils";
+import { createPartnerSchema } from "../zod/schemas/partners";
import {
EMBED_PUBLIC_TOKEN_EXPIRY,
EMBED_PUBLIC_TOKEN_LENGTH,
EMBED_PUBLIC_TOKEN_PREFIX,
} from "./constants";
-interface EmbedTokenProps {
+type EmbedTokenProps = {
programId: string;
- partnerId: string;
-}
+ partnerId?: string;
+ partner?: Omit<z.infer<typeof createPartnerSchema>, "programId">;
+};
class EmbedToken {
async create(props: EmbedTokenProps) {
diff --git a/apps/web/lib/zod/schemas/token.ts b/apps/web/lib/zod/schemas/token.ts
index 694456314d..7a0681741c 100644
--- a/apps/web/lib/zod/schemas/token.ts
+++ b/apps/web/lib/zod/schemas/token.ts
@@ -1,5 +1,6 @@
import { SCOPES } from "@/lib/api/tokens/scopes";
import z from "@/lib/zod";
+import { createPartnerSchema } from "./partners";
// Schema to validate the request body when creating a new token
export const createTokenSchema = z.object({
@@ -41,11 +42,22 @@ export const tokenSchema = z.object({
}),
});
-export const createEmbedTokenSchema = z.object({
- programId: z.string().min(1),
- partnerId: z.string().nullish(),
- tenantId: z.string().nullish(),
-});
+export const createEmbedTokenSchema = z.union([
+ z.object({
+ programId: z.string(),
+ partnerId: z.string(),
+ }),
+
+ z.object({
+ programId: z.string(),
+ tenantId: z.string(),
+ }),
+
+ z.object({
+ programId: z.string(),
+ partner: createPartnerSchema.omit({ programId: true }),
+ }),
+]);
export const EmbedTokenSchema = z.object({
publicToken: z.string(),