The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add QR code and analytics endpoints
Kiran Kccff2e3ad15e
diff --git a/apps/web/app/api/analytics/[endpoint]/route.ts b/apps/web/app/api/analytics/[endpoint]/route.tsindex fae3274ef2..8e336b5890 100644--- a/apps/web/app/api/analytics/[endpoint]/route.ts+++ b/apps/web/app/api/analytics/[endpoint]/route.ts@@ -1,37 +1,56 @@-import { getAnalytics } from "@/lib/analytics";+import { VALID_TINYBIRD_ENDPOINTS, getAnalytics } from "@/lib/analytics";import { withAuth } from "@/lib/auth";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/errors";import { getDomainViaEdge } from "@/lib/planetscale";+import z from "@/lib/zod";+import { getAnalyticsQuerySchema } from "@/lib/zod/schemas/analytics";import { NextResponse } from "next/server";+export const endpointSchema = z.object({+ endpoint: z.enum(VALID_TINYBIRD_ENDPOINTS, {+ errorMap: (issue, ctx) => {+ return {+ message: `Invalid endpoint. Valid endpoints are: ${VALID_TINYBIRD_ENDPOINTS.join(", ")}`,+ };+ },+ }),+});+// GET /api/analytics/[endpoint] – get analytics for a specific endpointexport const GET = withAuth(async ({ params, searchParams, project, link }) => {- const { endpoint } = params;- let { domain, key, interval } = searchParams;+ try {+ const { endpoint } = endpointSchema.parse(params);+ const parsedParams = getAnalyticsQuerySchema.parse(searchParams);+ const { domain, key, interval } = parsedParams;- // return 403 if project is on the free plan and interval is 90d or all- if (- project?.plan === "free" &&- (interval === "all" || interval === "90d")- ) {- return new Response(`Require higher plan`, { status: 403 });- }+ // return 403 if project is on the free plan and interval is 90d or all+ if (+ project?.plan === "free" &&+ (interval === "all" || interval === "90d")+ ) {+ throw new DubApiError({+ code: "forbidden",+ message: "Require higher plan",+ });+ }- const linkId = link- ? link.id- : domain && key === "_root"- ? await getDomainViaEdge(domain).then((d) => d?.id)- : null;+ const linkId = link+ ? link.id+ : domain && key === "_root"+ ? await getDomainViaEdge(domain).then((d) => d?.id)+ : null;- const response = await getAnalytics({- projectId: project.id,- ...(linkId && { linkId }),- domain,- endpoint,- interval,- ...searchParams,- });- return NextResponse.json(response);+ const response = await getAnalytics({+ projectId: project.id,+ ...(linkId && { linkId }),+ endpoint,+ ...parsedParams,+ });+ return NextResponse.json(response);+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }},{needNotExceededClicks: true,diff --git a/apps/web/lib/analytics.ts b/apps/web/lib/analytics.tsindex 023c441f1c..278d9ae538 100644--- a/apps/web/lib/analytics.ts+++ b/apps/web/lib/analytics.ts@@ -1,6 +1,10 @@import { conn } from "./planetscale";+import z from "./zod";+import { getAnalyticsQuerySchema } from "./zod/schemas/analytics";-export type IntervalProps = "1h" | "24h" | "7d" | "30d" | "90d" | "all";+export const intervals = ["1h", "24h", "7d", "30d", "90d", "all"] as const;++export type IntervalProps = (typeof intervals)[number];export const INTERVALS = [{@@ -61,7 +65,7 @@ export type LocationTabs = "country" | "city";export type TopLinksTabs = "link" | "url";export type DeviceTabs = "device" | "browser" | "os" | "ua";-const VALID_TINYBIRD_ENDPOINTS = [+export const VALID_TINYBIRD_ENDPOINTS = ["timeseries","clicks","top_links",@@ -73,7 +77,7 @@ const VALID_TINYBIRD_ENDPOINTS = ["browser","os","referer",-];+] as const;export const VALID_ANALYTICS_FILTERS = ["country",@@ -94,14 +98,10 @@ export const getAnalytics = async ({endpoint,interval,...rest-}: {+}: z.infer<typeof getAnalyticsQuerySchema> & {projectId?: string;linkId?: string;- domain?: string;- endpoint: string;- interval?: string;-} & {- [key in (typeof VALID_ANALYTICS_FILTERS)[number]]: string;+ endpoint: (typeof VALID_TINYBIRD_ENDPOINTS)[number];}) => {// Note: we're using decodeURIComponent in this function because that's how we store it in MySQL and Tinybirddiff --git a/apps/web/lib/openapi/analytics/clicks.ts b/apps/web/lib/openapi/analytics/clicks.tsnew file mode 100644index 0000000000..2e454b3d5e--- /dev/null+++ b/apps/web/lib/openapi/analytics/clicks.ts@@ -0,0 +1,29 @@+import { openApiErrorResponses } from "@/lib/openapi/responses";+import { getAnalyticsQuerySchema } from "@/lib/zod/schemas/analytics";+import { ZodOpenApiOperationObject } from "zod-openapi";++export const getClickAnalytics: ZodOpenApiOperationObject = {+ operationId: "getClicksAnalytics",+ summary: "Retrieve clicks analytics",+ description:+ "Retrieve the number of clicks for a link, a domain, or the authenticated project.",+ requestParams: {+ query: getAnalyticsQuerySchema,+ },+ responses: {+ "200": {+ description: "The number of clicks",+ content: {+ "application/json": {+ schema: {+ type: "number",+ description: "The number of clicks",+ },+ },+ },+ },+ ...openApiErrorResponses,+ },+ tags: ["Analytics"],+ security: [{ bearerToken: [] }],+};diff --git a/apps/web/lib/openapi/analytics/index.ts b/apps/web/lib/openapi/analytics/index.tsnew file mode 100644index 0000000000..27c5c7b203--- /dev/null+++ b/apps/web/lib/openapi/analytics/index.ts@@ -0,0 +1,13 @@+import { ZodOpenApiPathsObject } from "zod-openapi";++import { getClickAnalytics } from "./clicks";+import { getTimeseriesAnalytics } from "./timeseries";++export const analyticsPaths: ZodOpenApiPathsObject = {+ "/analytics/clicks": {+ get: getClickAnalytics,+ },+ "/analytics/timeseries": {+ get: getTimeseriesAnalytics,+ },+};diff --git a/apps/web/lib/openapi/analytics/timeseries.ts b/apps/web/lib/openapi/analytics/timeseries.tsnew file mode 100644index 0000000000..e3de4917fd--- /dev/null+++ b/apps/web/lib/openapi/analytics/timeseries.ts@@ -0,0 +1,36 @@+import { openApiErrorResponses } from "@/lib/openapi/responses";+import z from "@/lib/zod";+import { getAnalyticsQuerySchema } from "@/lib/zod/schemas/analytics";+import { ZodOpenApiOperationObject } from "zod-openapi";++export const getTimeseriesAnalytics: ZodOpenApiOperationObject = {+ operationId: "getTimeseriesAnalytics",+ summary: "Retrieve timeseries analytics",+ description:+ "Retrieve the number of clicks for a link, a domain, or the authenticated project over a period of time.",+ requestParams: {+ query: getAnalyticsQuerySchema,+ },+ responses: {+ "200": {+ description: "The number of clicks over a period of time",+ content: {+ "application/json": {+ schema: z.array(+ z.object({+ start: z+ .string()+ .describe("The starting timestamp of the interval"),+ clicks: z+ .number()+ .describe("The number of clicks in the interval"),+ }),+ ),+ },+ },+ },+ ...openApiErrorResponses,+ },+ tags: ["Analytics"],+ security: [{ bearerToken: [] }],+};diff --git a/apps/web/lib/openapi/index.ts b/apps/web/lib/openapi/index.tsindex b3435a6387..5516ffdb46 100644--- a/apps/web/lib/openapi/index.ts+++ b/apps/web/lib/openapi/index.ts@@ -3,8 +3,10 @@ import { ZodOpenApiObject } from "zod-openapi";import { LinkSchema } from "@/lib/zod/schemas/links";import { projectSchema } from "@/lib/zod/schemas/projects";import { tagSchema } from "@/lib/zod/schemas/tags";+import { analyticsPaths } from "./analytics";import { linksPaths } from "./links";import { projectsPaths } from "./projects";+import { qrCodePaths } from "./qr";import { tagsPaths } from "./tags";export const openApiObject: ZodOpenApiObject = {@@ -31,7 +33,9 @@ export const openApiObject: ZodOpenApiObject = {},],paths: {+ ...analyticsPaths,...linksPaths,+ ...qrCodePaths,...projectsPaths,...tagsPaths,},diff --git a/apps/web/lib/openapi/links/index.ts b/apps/web/lib/openapi/links/index.tsindex 5a7794f5e0..4448adc143 100644--- a/apps/web/lib/openapi/links/index.ts+++ b/apps/web/lib/openapi/links/index.ts@@ -6,7 +6,6 @@ import { deleteLink } from "./delete-link";import { editLink } from "./edit-link";import { getLinkInfo } from "./get-link-info";import { getLinks } from "./get-links";-import { getQRCode } from "./get-qr";export const linksPaths: ZodOpenApiPathsObject = {"/links": {@@ -23,7 +22,4 @@ export const linksPaths: ZodOpenApiPathsObject = {"/links/bulk": {post: createBulkLink,},- "/qr": {- get: getQRCode,- },};diff --git a/apps/web/lib/openapi/links/get-qr.ts b/apps/web/lib/openapi/qr/get-qr.tssimilarity index 96%rename from apps/web/lib/openapi/links/get-qr.tsrename to apps/web/lib/openapi/qr/get-qr.tsindex 5ab1eb1c36..abc4ff3506 100644--- a/apps/web/lib/openapi/links/get-qr.ts+++ b/apps/web/lib/openapi/qr/get-qr.ts@@ -21,6 +21,6 @@ export const getQRCode: ZodOpenApiOperationObject = {},...openApiErrorResponses,},- tags: ["Links"],+ tags: ["QR Codes"],security: [{ bearerToken: [] }],};diff --git a/apps/web/lib/openapi/qr/index.ts b/apps/web/lib/openapi/qr/index.tsnew file mode 100644index 0000000000..edd5db3142--- /dev/null+++ b/apps/web/lib/openapi/qr/index.ts@@ -0,0 +1,9 @@+import { ZodOpenApiPathsObject } from "zod-openapi";++import { getQRCode } from "./get-qr";++export const qrCodePaths: ZodOpenApiPathsObject = {+ "/qr": {+ get: getQRCode,+ },+};diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.tsnew file mode 100644index 0000000000..42cb904144--- /dev/null+++ b/apps/web/lib/zod/schemas/analytics.ts@@ -0,0 +1,45 @@+import { intervals } from "@/lib/analytics";+import z from "@/lib/zod";+import { booleanQuerySchema } from ".";++// TODO:+// Use COUNTRIES code enum++export const getAnalyticsQuerySchema = z.object({+ projectSlug: z+ .string()+ .min(1, "Project slug is required.")+ .describe(+ "The slug for the project that the link belongs to. E.g. for `app.dub.co/acme`, the projectSlug is `acme`.",+ ),+ domain: z.string().optional().describe("The domain of the short link."),+ key: z.string().optional().describe("The short link slug."),+ interval: z+ .enum(intervals)+ .optional()+ .default("24h")+ .describe("The interval to retrieve analytics for."),+ country: z+ .string()+ .optional()+ .describe("The country to retrieve analytics for."),+ city: z.string().optional().describe("The city to retrieve analytics for."),+ device: z+ .string()+ .optional()+ .describe("The device to retrieve analytics for."),+ browser: z+ .string()+ .optional()+ .describe("The browser to retrieve analytics for."),+ os: z.string().optional().describe("The OS to retrieve analytics for."),+ referer: z+ .string()+ .optional()+ .describe("The referer to retrieve analytics for."),+ url: z.string().optional().describe("The URL to retrieve analytics for."),+ excludeRoot: booleanQuerySchema+ .optional()+ .default("false")+ .describe("Whether to exclude the root link from the response."),+});