From 40e6acfaf372f418ef7b1fb4982da51feee848d8 Mon Sep 17 00:00:00 2001 From: Jordi Enric Date: Fri, 3 May 2024 19:59:08 +0200 Subject: [PATCH] test tinybird --- apps/web/src/analytics/index.ts | 33 +++++++++++++++++++ .../pages/api/public/[blogId]/post/[slug].ts | 10 +++++- 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/analytics/index.ts diff --git a/apps/web/src/analytics/index.ts b/apps/web/src/analytics/index.ts new file mode 100644 index 0000000..798203d --- /dev/null +++ b/apps/web/src/analytics/index.ts @@ -0,0 +1,33 @@ +export function sendViewEvent({ + blog_id, + post_id, + post_slug, + post_title, +}: { + blog_id: string; + post_id: string; + post_slug: string; + post_title: string; +}) { + fetch( + "https://api.eu-central-1.aws.tinybird.co/v0/events?name=events_example", + { + method: "POST", + body: JSON.stringify({ + timestamp: new Date().toISOString(), + blog_id, + post_id, + post_slug, + post_title, + event_type: "post_view", + }), + headers: { + Authorization: `Bearer ${process.env.TINYBIRD_TOKEN}`, + }, + } + ).then((res) => { + if (!res.ok) { + throw new Error("Failed to send event"); + } + }); +} diff --git a/apps/web/src/pages/api/public/[blogId]/post/[slug].ts b/apps/web/src/pages/api/public/[blogId]/post/[slug].ts index 92148f8..9f334d9 100644 --- a/apps/web/src/pages/api/public/[blogId]/post/[slug].ts +++ b/apps/web/src/pages/api/public/[blogId]/post/[slug].ts @@ -1,3 +1,4 @@ +import { sendViewEvent } from "@/analytics"; import { createAdminClient } from "@/lib/server/supabase"; import { NextApiRequest, NextApiResponse } from "next"; @@ -19,7 +20,7 @@ export default async function handler( const postPromise = db .from("posts") .select( - "slug, title, content, cover_image, published_at, created_at, updated_at, metadata" + "id, slug, title, content, cover_image, published_at, created_at, updated_at, metadata" ) .eq("blog_id", blogId) .eq("published", true) @@ -46,6 +47,13 @@ export default async function handler( .eq("user_id", ownerId) .single(); + sendViewEvent({ + blog_id: blogId, + post_id: post?.id || "", + post_slug: post?.slug || "", + post_title: post?.title || "", + }); + if (subscription?.status !== "active") { return res.status(401).json({ error: "UNAUTHORIZED" }); }