-
-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathapi.ts
More file actions
344 lines (300 loc) · 9.5 KB
/
api.ts
File metadata and controls
344 lines (300 loc) · 9.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import {
LinkedInProfile,
MediumBlog,
Profile,
UserProject,
} from "@/types/types";
import { parseStringPromise } from "xml2js";
const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL;
const API_KEY = process.env.NEXT_PUBLIC_X_API_KEY;
// Utility function to detect provider from URL
const detectProvider = (url: string): string => {
const urlLower = url.toLowerCase();
if (urlLower.includes('medium.com')) return 'medium';
if (urlLower.includes('instagram.com')) return 'instagram';
if (urlLower.includes('huggingface.co')) return 'huggingface';
return 'generic';
};
/**
* Fetch resource with Next.js caching
*/
const fetchResource = async <T>(
endpoint: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options: any = {},
): Promise<T | null> => {
try {
const url = `${BASE_URL}${endpoint}`;
const response = await fetch(url, {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"X-Api-Key": API_KEY || "",
},
next: {
revalidate: 3600, // Revalidate every hour
...options.next,
},
});
if (!response.ok) {
throw new Error(`Error fetching ${endpoint}: ${response.status}`);
}
return response.json() as Promise<T>;
} catch (error) {
// @ts-expect-error -- asflasdlkfjasdlf
if (error?.name === "AbortError") {
console.error(`Request timeout for ${endpoint}`);
} else {
console.error(`Error fetching ${endpoint}:`, error);
}
return null;
}
};
/**
* Get user profile data
*/
export const getUserProfile = async (
username: string,
): Promise<Profile | null> => {
if (!username) return null;
return fetchResource<Profile>(`/user/${username}/profile`);
};
/**
* Get user projects data
*/
export const getUserProjects = async (
username: string,
): Promise<UserProject | null> => {
if (!username) return null;
return fetchResource<UserProject>(`/user/${username}/projects`);
};
/**
* Get user LinkedIn profile data
*/
export const getUserLinkedInProfile = async (
username: string,
): Promise<LinkedInProfile | null> => {
try {
if (!username) return null;
// Add a cache tag for better revalidation
const data = await fetchResource<LinkedInProfile>(
`/user/${username}/linkedin`,
{
next: {
revalidate: 3600, // 1 hour
tags: [`linkedin-${username}`],
},
},
);
// Validate the returned data structure
if (!data || !data.basic_info) {
console.warn(`Invalid LinkedIn data structure for user: ${username}`);
return null;
}
return data;
} catch (error) {
console.error(`Error fetching LinkedIn data for ${username}:`, error);
return null;
}
};
/**
* Get user Medium blogs
*/
export const getUserMediumBlogs = async (
username: string,
): Promise<MediumBlog[] | null> => {
if (!username) return null;
try {
// Build the URL for the user's Medium RSS feed
const url = `https://medium.com/feed/@${username}`;
const response = await fetch(url, {
next: {
revalidate: 3600, // Revalidate every hour
},
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const xmlData = await response.text();
// Parse the XML response
const parser = { explicitArray: false };
const result = await parseStringPromise(xmlData, parser);
// Check if we have items in the feed
if (!result.rss || !result.rss.channel || !result.rss.channel.item) {
console.log("No items found in the RSS feed");
return [];
}
// Get all items (make sure it's an array even if there's only one item)
const items = Array.isArray(result.rss.channel.item)
? result.rss.channel.item
: [result.rss.channel.item];
// Format the blog posts
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return items.map((item: any) => {
// Try to extract thumbnail image from content
let thumbnail = "";
// First try to get image from content:encoded
if (item["content:encoded"]) {
// Look for the first image tag with src attribute
const imgMatch = item["content:encoded"].match(
/<img[^>]+src="([^">]+)"/,
);
if (imgMatch && imgMatch[1]) {
thumbnail = imgMatch[1];
}
}
// If no image found in content, try to get from media:content
if (!thumbnail && item["media:content"] && item["media:content"].$.url) {
thumbnail = item["media:content"].$.url;
}
// If still no image, check for enclosure
if (!thumbnail && item.enclosure && item.enclosure.$.url) {
thumbnail = item.enclosure.$.url;
}
// If still no image, try to find an image URL in the description
if (!thumbnail && item.description) {
const descImgMatch = item.description.match(/<img[^>]+src="([^">]+)"/);
if (descImgMatch && descImgMatch[1]) {
thumbnail = descImgMatch[1];
}
}
return {
title: item.title || "No title",
link: item.link || "",
pubDate: item.pubDate || "",
// Remove HTML tags from content
preview: item["content:encoded"]
? item["content:encoded"].replace(/<[^>]*>/g, "")
: "No preview available",
// Get categories if available
categories: item.category
? Array.isArray(item.category)
? item.category.join(", ")
: item.category
: "",
thumbnail: thumbnail,
};
});
} catch (error) {
console.error(`Error fetching Medium blogs: ${error}`);
return null;
}
};
/**
* Get user profile data (server-side)
*/
export const getProfileData = async (
username: string,
): Promise<Profile | null> => {
if (!username) return null;
return fetchResource<Profile>(`/user/${username}/profile`);
};
/**
* Get user projects data (server-side)
*/
export const getProjectData = async (
username: string,
): Promise<UserProject | null> => {
if (!username) return null;
return fetchResource<UserProject>(`/user/${username}/projects`);
};
/**
* Get user LinkedIn profile data (server-side)
*/
export const getLinkedInProfileData = async (
username: string,
): Promise<LinkedInProfile | null> => {
if (!username) return null;
return fetchResource<LinkedInProfile>(`/user/${username}/linkedin`);
};
/**
* API to add user to Supabase via edge function for analytics
*/
export const addUserToSupabase = async (user: Profile | null, searchParams?: URLSearchParams) => {
if (!user) return;
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseAnonKey = process.env.SUPABASE_KEY;
if (!supabaseUrl || !supabaseAnonKey) {
console.error("Supabase configuration missing");
return;
}
const url = `${supabaseUrl}/functions/v1/devb-io`;
// Map user data to match Supabase function whitelist
const mappedData: Record<string, string> = {
name: user.username,
"full name": user.name,
"devb profile": `https://devb.io/${user.username}`,
github: `https://github.com/${user.username}`,
};
// Add query parameters if available
if (searchParams) {
// UTM parameters
const utmSource = searchParams.get('utm_source');
const utmMedium = searchParams.get('utm_medium');
const utmCampaign = searchParams.get('utm_campaign');
const utmTerm = searchParams.get('utm_term');
const utmContent = searchParams.get('utm_content');
// Referral parameter
const ref = searchParams.get('ref');
// Add to mapped data if they exist
if (utmSource) mappedData['utm_source'] = utmSource;
if (utmMedium) mappedData['utm_medium'] = utmMedium;
if (utmCampaign) mappedData['utm_campaign'] = utmCampaign;
if (utmTerm) mappedData['utm_term'] = utmTerm;
if (utmContent) mappedData['utm_content'] = utmContent;
if (ref) mappedData['ref'] = ref;
}
// Counter for generic URLs
let genericCounter = 1;
// Add social accounts based on provider
user.social_accounts?.forEach((account) => {
const provider = account.provider.toLowerCase();
// If provider is generic, detect the actual platform
const actualProvider = provider === "generic" ? detectProvider(account.url) : provider;
switch (actualProvider) {
case "linkedin":
mappedData["Linkedin"] = account.url;
break;
case "twitter":
mappedData["twitter"] = account.url;
break;
case "medium":
mappedData["Medium"] = account.url;
break;
case "instagram":
mappedData["instagram"] = account.url;
break;
case "huggingface":
// Could add huggingface to whitelist if needed
break;
case "generic":
// Check if it's a devb.io link
if (account.url.includes("devb.io")) {
mappedData["devb"] = account.url;
} else {
// For other generic URLs, number them
mappedData[`generic ${genericCounter}`] = account.url;
genericCounter++;
}
break;
}
});
const headers = {
"Content-Type": "application/json",
"Authorization": `Bearer ${supabaseAnonKey}`,
};
try {
const response = await fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify(mappedData),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log("User data sent to Supabase:", result);
} catch (error) {
console.error("Error sending data to Supabase:", error);
}
};