78 lines
2.1 KiB
JavaScript
78 lines
2.1 KiB
JavaScript
import { getNotionDatabaseWithCache } from '../utils/notion.js';
|
|
import { globalHeaders } from '../utils/api.js';
|
|
const socialsDB = SOCIALS_DB;
|
|
const referrersDB = REFERRERS_DB;
|
|
|
|
export async function handleSocialsRequest(request, env) {
|
|
console.log('Listing socials...');
|
|
try {
|
|
// Parse URL to get query parameters
|
|
const url = new URL(request.url);
|
|
const referrer = url.searchParams.get('r') || 'unknown';
|
|
|
|
console.log('Referrer:', referrer);
|
|
|
|
// Get social links from Notion (with caching)
|
|
const socialsData = await getNotionDatabaseWithCache(socialsDB);
|
|
|
|
// Get referrers from Notion (with caching)
|
|
const referrersData = await getNotionDatabaseWithCache(referrersDB, {
|
|
filter: {
|
|
property: 'Slug',
|
|
rich_text: {
|
|
equals: referrer,
|
|
},
|
|
},
|
|
});
|
|
|
|
if (referrersData.length <= 0) {
|
|
console.error('Invalid referrer.');
|
|
return new Response(
|
|
JSON.stringify({
|
|
error: 'Invalid referrer.',
|
|
}),
|
|
{
|
|
status: 404,
|
|
headers: globalHeaders,
|
|
},
|
|
);
|
|
}
|
|
|
|
const referrerObject = referrersData[0];
|
|
|
|
var socialsResponse = [];
|
|
|
|
// Loop through each relation
|
|
for (const relation of referrerObject.properties['Social Media'].relation) {
|
|
console.log('Social ID:', relation.id);
|
|
const socialMedia = Object.fromEntries(socialsData.map((social) => [social.id, social]))[relation.id];
|
|
const socialsResponseObject = {
|
|
name: socialMedia.properties['Name'].title[0].plain_text,
|
|
icon: socialMedia.properties['Icon'].rich_text[0].plain_text,
|
|
url: socialMedia.properties['Link'].url,
|
|
};
|
|
socialsResponse.push(socialsResponseObject);
|
|
}
|
|
// Return the processed data
|
|
console.log('Finished listing socials.');
|
|
return new Response(JSON.stringify(socialsResponse), {
|
|
headers: {
|
|
...globalHeaders,
|
|
'Cache-Control': 'public, max-age=600', // 10 minute browser cache
|
|
},
|
|
});
|
|
} catch (error) {
|
|
console.error('Error handling socials request:', error);
|
|
return new Response(
|
|
JSON.stringify({
|
|
error: 'Failed to retrieve social links',
|
|
message: error.message,
|
|
}),
|
|
{
|
|
status: 500,
|
|
headers: globalHeaders,
|
|
},
|
|
);
|
|
}
|
|
}
|