The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
made repo work without env vars
Steven Tey62a9066b8dde
diff --git a/components/home/link-card.tsx b/components/home/link-card.tsxindex 8e3f93bfc0..5fd912be17 100644--- a/components/home/link-card.tsx+++ b/components/home/link-card.tsx@@ -174,7 +174,7 @@ export default function LinkCard({><Chart className="h-4 w-4" /><p className="text-sm">- {!clicks && clicks != 0 ? (+ {!clicks && clicks !== 0 ? (<LoadingDots color="#71717A" />) : (nFormatter(clicks)diff --git a/components/home/testimonials.tsx b/components/home/testimonials.tsxindex 631709764b..3d6cbda7fc 100644--- a/components/home/testimonials.tsx+++ b/components/home/testimonials.tsx@@ -25,8 +25,8 @@ export default function Testimonials({<div className="space-y-6 py-8 sm:columns-2 sm:gap-6 xl:columns-3">{tweets.map((tweet, idx) => (<Tweet- key={tweet.id}- id={tweet.id}+ key={idx}+ id={idx.toString()}metadata={JSON.stringify(tweet)}className={idx < Math.floor(tweets.length / 3) ||diff --git a/components/shared/tweet.tsx b/components/shared/tweet.tsxindex 04fa7bda22..c56bc4d44f 100644--- a/components/shared/tweet.tsx+++ b/components/shared/tweet.tsx@@ -29,9 +29,23 @@ export default function Tweet({metadata: any;className?: string;}) {- const parsedMetadata = JSON.parse(metadata.replace(/\n/g, "\\n"));+ if (!metadata || metadata === "null") {+ return (+ <div+ className={`${className} prose flex h-[20rem] break-inside-avoid items-center rounded-lg border border-gray-300 bg-white/20 bg-clip-padding p-6 pb-4 text-center text-sm backdrop-blur-lg backdrop-filter`}+ >+ <p>+ There was an error loading this tweet. Did you specify the{" "}+ <code className="rounded-md bg-red-50 p-1 text-red-600">+ TWITTER_AUTH_TOKEN+ </code>{" "}+ environment variable?+ </p>+ </div>+ );+ }- // console.log(JSON.stringify(parsedMetadata, null, 4));+ const parsedMetadata = JSON.parse(metadata.replace(/\n/g, "\\n"));const text = parsedMetadata.text;const author = parsedMetadata.author;diff --git a/lib/planetscale.ts b/lib/planetscale.tsindex b325d7cc39..b69fd633d7 100644--- a/lib/planetscale.ts+++ b/lib/planetscale.ts@@ -1,12 +1,14 @@import { connect } from "@planetscale/database";export const pscale_config = {- url: process.env["DATABASE_URL"] || "mysql://user:pass@host",+ url: process.env.DATABASE_URL || "mysql://user:pass@host",};-export const conn = connect(pscale_config);+export const conn = process.env.DATABASE_URL ? connect(pscale_config) : null;export async function getLinkViaEdge(domain: string, key: string) {+ if (!conn) return null;+const { rows } =(await conn.execute("SELECT `key`, url, clicks, userId, publicStats FROM Link WHERE domain = ? AND `key` = ?",diff --git a/lib/stats.ts b/lib/stats.tsindex a81c5a0236..2a613d80df 100644--- a/lib/stats.ts+++ b/lib/stats.ts@@ -118,12 +118,20 @@ export const getStats = async ({endpoint: string;interval?: string;}) => {+ if (!process.env.TINYBIRD_API_KEY) {+ return null;+ }+if (!VALID_TINYBIRD_ENDPOINTS.has(endpoint)) {return null;}- // get all-time clicks count- if (endpoint === "clicks" && !interval) {+ // get all-time clicks count if:+ // 1. endpoint is /clicks+ // 2. interval is not defined+ // 3. there's a connection to MySQL++ if (endpoint === "clicks" && !interval && conn) {const response = await conn.execute("SELECT clicks FROM Link WHERE domain = ? AND `key` = ?",[domain, key],diff --git a/lib/twitter/get-tweet.ts b/lib/twitter/get-tweet.tsindex 06566c61b7..08b5094943 100644--- a/lib/twitter/get-tweet.ts+++ b/lib/twitter/get-tweet.ts@@ -1,101 +1,109 @@-import querystring from "querystring";+import { stringify as queryStringify } from "querystring";+import { getTwitterMedia } from "./twitter-media";-export const getTweet = async (id: string) => {- const queryParams = querystring.stringify({- expansions:- "author_id,attachments.media_keys,referenced_tweets.id,referenced_tweets.id.author_id,attachments.poll_ids",- "tweet.fields":- "attachments,author_id,public_metrics,created_at,id,in_reply_to_user_id,referenced_tweets,text,entities",- "user.fields": "id,name,profile_image_url,protected,url,username,verified",- "media.fields":- "duration_ms,height,media_key,preview_image_url,type,url,width,public_metrics",- "poll.fields": "duration_minutes,end_datetime,id,options,voting_status",- });+const queryParams = queryStringify({+ expansions:+ "author_id,attachments.media_keys,referenced_tweets.id,referenced_tweets.id.author_id,attachments.poll_ids",+ "tweet.fields":+ "attachments,author_id,public_metrics,created_at,id,in_reply_to_user_id,referenced_tweets,text,entities",+ "user.fields": "id,name,profile_image_url,protected,url,username,verified",+ "media.fields":+ "duration_ms,height,media_key,preview_image_url,type,url,width,public_metrics",+ "poll.fields": "duration_minutes,end_datetime,id,options,voting_status",+});- const response = await fetch(- `https://api.twitter.com/2/tweets/${id}?${queryParams}`,- {- headers: {- Authorization: `Bearer ${process.env.TWITTER_AUTH_TOKEN}`,+export const getTweet = async (id: string) => {+ try {+ const response = await fetch(+ `https://api.twitter.com/2/tweets/${id}?${queryParams}`,+ {+ headers: {+ Authorization: `Bearer ${process.env.TWITTER_AUTH_TOKEN}`,+ },},- },- );-- const tweet = await response.json();+ );+ const tweet = await response.json();- //console.log(JSON.stringify(tweet, null, 4));+ if (!tweet.data)+ throw new Error(`Failed to get tweet data for tweet ID: ${id}`);- const getAuthorInfo = (author_id) => {- return tweet.includes.users.find((user) => user.id === author_id);- };+ const getAuthorInfo = (author_id: string) =>+ tweet.includes.users.find((user) => user.id === author_id);- const getReferencedTweets = (mainTweet) => {- return (+ const getReferencedTweets = (mainTweet) =>mainTweet?.referenced_tweets?.map((referencedTweet) => {- const fullReferencedTweet = tweet.includes.tweets.find(+ const fullReferencedTweet = tweet.includes.tweets?.find((tweet) => tweet.id === referencedTweet.id,);+ if (!fullReferencedTweet)+ throw new Error(+ `Failed to find full tweet from referenced tweet ID: ${referencedTweet.id}`,+ );return {type: referencedTweet.type,- author: getAuthorInfo(fullReferencedTweet.author_id),...fullReferencedTweet,};- }) || []+ }) || [];++ // Function to distinguish between external URLs and external t.co links and internal t.co links+ // (e.g. images, videos, gifs, quote tweets) and remove/replace them accordingly++ if (tweet.data) tweet.data.text = getExternalUrls(tweet?.data); // removing/replacing t.co links for main tweet+ tweet?.includes?.tweets?.map((twt) => {+ // removing/replacing t.co links for referenced tweets+ twt.text = getExternalUrls(twt);+ });++ const media = tweet.data?.attachments?.media_keys?.map((key) =>+ tweet.includes.media?.find((media) => media.media_key === key),);- };-- // function to distinguish between external URLs and external t.co links and internal t.co links- // (e.g. images, videos, gifs, quote tweets) and remove/replace them accordingly- const getExternalUrls = (tweet) => {- const externalURLs = tweet.entities?.urls;- const mappings = {};- if (externalURLs) {- externalURLs.map((url) => {- mappings[`${url.url}`] =- !url.display_url.startsWith("pic.twitter.com") &&- !url.display_url.startsWith("twitter.com")- ? `<a style='color: rgb(29,161,242); font-weight:normal; text-decoration: none' href='${url.expanded_url.replace(- "@",- "",- )}' target='_blank'>${url.display_url.replace("@", "")}</a>`- : "";- });- }- var processedText = tweet.text;- Object.entries(mappings).map(([k, v], i) => {- processedText = processedText.replace(k, v);++ const referenced_tweets = getReferencedTweets(tweet.data);++ return {+ ...tweet.data,+ author: getAuthorInfo(tweet.data?.author_id),+ media: media || [],+ polls: tweet?.includes?.polls || [],+ referenced_tweets: referenced_tweets,+ url_meta:+ media || referenced_tweets.length > 0 || !tweet.data?.entities?.urls+ ? null+ : tweet.data?.entities?.urls[0],+ video:+ media &&+ media[0] &&+ (media[0].type === "video" || media[0].type === "animated_gif")+ ? await getTwitterMedia(id)+ : null,+ };+ } catch (error) {+ return null;+ }+};++function getExternalUrls(tweet) {+ const externalURLs = tweet?.entities?.urls;++ let mappings: {+ [I in string]: string;+ } = {};++ if (externalURLs)+ externalURLs.map((url) => {+ mappings[url.url] =+ !url.display_url.startsWith("pic.twitter.com") &&+ !url.display_url.startsWith("twitter.com")+ ? url.expanded_url+ : "";});- return processedText;- };- tweet.data.text = getExternalUrls(tweet.data); // removing/replacing t.co links for main tweet- tweet?.includes?.tweets?.map((twt) => {- // removing/replacing t.co links for referenced tweets- twt.text = getExternalUrls(twt);++ let processedText = tweet?.text;+ Object.entries(mappings).map(([key, value]) => {+ processedText = processedText.replace(key, value);});- const media = tweet.data?.attachments?.media_keys?.map((key) =>- tweet.includes.media.find((media) => media.media_key === key),- );-- const referenced_tweets = getReferencedTweets(tweet.data);-- return {- ...tweet.data,- media: media || [],- video:- media && (media[0].type == "video" || media[0].type == "animated_gif")- ? await getTwitterMedia(id)- : null,- polls: tweet.includes.polls || [],- url_meta:- media ||- referenced_tweets.length > 0 ||- tweet.data?.entities?.urls == undefined- ? null- : tweet.data.entities?.urls[0],- referenced_tweets: referenced_tweets,- author: getAuthorInfo(tweet.data.author_id),- };-};+ return processedText;+}diff --git a/lib/upstash.ts b/lib/upstash.tsindex bd5af70f7b..38dc8db299 100644--- a/lib/upstash.ts+++ b/lib/upstash.ts@@ -9,11 +9,14 @@ export const redis = new Redis({});// Create a new ratelimiter, that allows 10 requests per 10 seconds-export const ratelimit = new Ratelimit({- redis: Redis.fromEnv(),- limiter: Ratelimit.slidingWindow(10, "10 s"),- analytics: true,-});+export const ratelimit =+ process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN+ ? new Ratelimit({+ redis: Redis.fromEnv(),+ limiter: Ratelimit.slidingWindow(10, "10 s"),+ analytics: true,+ })+ : null;// only for dub.sh public demoexport async function setRandomKey(diff --git a/pages/api/edge/coordinates.ts b/pages/api/edge/coordinates.tsindex 29624b5154..44ddd8e65a 100644--- a/pages/api/edge/coordinates.ts+++ b/pages/api/edge/coordinates.ts@@ -7,24 +7,28 @@ export const config = {export default async function handler(req: NextRequest) {if (req.method === "GET") {const count = 50;+ let latestCoordinates = [];- const response = await fetch(- `https://api.us-east.tinybird.co/v0/pipes/coordinates.json`,- {- headers: {- Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,+ if (process.env.TINYBIRD_API_KEY) {+ const response = await fetch(+ `https://api.us-east.tinybird.co/v0/pipes/coordinates.json`,+ {+ headers: {+ Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,+ },},- },- )- .then((res) => res.json())- .then((res) => res.data);+ )+ .then((res) => res.json())+ .then((res) => res.data);++ latestCoordinates = response.map(({ latitude, longitude }, idx) => {+ return {+ location: [latitude, longitude],+ size: 0.075 - (0.075 / count) * idx,+ };+ });+ }- const latestCoordinates = response.map(({ latitude, longitude }, idx) => {- return {- location: [latitude, longitude],- size: 0.075 - (0.075 / count) * idx,- };- });return new Response(JSON.stringify(latestCoordinates), {status: 200,headers: {diff --git a/pages/api/edge/links/[key]/stats/[endpoint].ts b/pages/api/edge/links/[key]/stats/[endpoint].tsindex 46de9da4a4..570a4e1c9f 100644--- a/pages/api/edge/links/[key]/stats/[endpoint].ts+++ b/pages/api/edge/links/[key]/stats/[endpoint].ts@@ -31,9 +31,6 @@ export default async function handler(req: NextRequest) {endpoint,interval,});- if (!response) {- return new Response(`Method ${req.method} Not Allowed`, { status: 405 });- }return new Response(JSON.stringify(response), { status: 200 });} else {diff --git a/pages/index.tsx b/pages/index.tsxindex a38df19ee5..c84b0cc3bc 100644--- a/pages/index.tsx+++ b/pages/index.tsx@@ -65,7 +65,7 @@ export default function Home({}export async function getStaticProps() {- const userCount = await prisma.user.count();+ const userCount = process.env.DATABASE_URL ? await prisma.user.count() : 5000;const { stargazers_count: stars } = await fetch("https://api.github.com/repos/steven-tey/dub",