Skip to content

Commit

Permalink
Merge branch 'main' into chore/deps
Browse files Browse the repository at this point in the history
  • Loading branch information
mbifulco authored Jan 2, 2024
2 parents 9ad5935 + 3c5ba86 commit 7d33ce7
Showing 1 changed file with 54 additions and 26 deletions.
80 changes: 54 additions & 26 deletions src/pages/api/newsletter/stats.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,69 @@
import type { NextApiRequest, NextApiResponse } from 'next';
// Importing only the necessary types from 'next'
import type { NextRequest } from 'next/server';

import { env } from '@utils/env.mjs';
// Environment variables should be accessed using the Next.js provided way for Edge Functions
const convertKitApiSecret = process.env.CONVERTKIT_API_SECRET;

type ResponseData = {
subscriberCount: number;
};

type ErrorResponse = {
message: string;
type ConvertKitStats = {
stats: {
total_subscribers: number;
open_tracking_enabled: boolean;
click_tracking_enabled: boolean;
subscribers_today: number;
subscribers_yesterday: number;
subscribers_last_7_days: number;
subscribers_previous_7_days: number;
subscribers_last_30_days: number;
subscribers_previous_30_days: number;
email_stats_mode: string;
sent: number;
clicked: number;
opened: number;
};
};

export default async function handler(
req: NextApiRequest,
res: NextApiResponse<ResponseData | ErrorResponse>
) {
export default async function handler(req: NextRequest) {
if (req.method !== 'GET') {
res.status(405).send({ message: 'Only GET requests allowed' });
return;
return new Response(
JSON.stringify({ message: 'Only GET requests allowed' }),
{
status: 405,
headers: {
'Content-Type': 'application/json',
},
}
);
}

// get newsletter subscriber count from ConvertKit API
const response = await fetch(
`https://api.convertkit.com/v3/lifetime_stats?api_secret=${env.CONVERTKIT_API_SECRET}`
`https://api.convertkit.com/v3/lifetime_stats?api_secret=${convertKitApiSecret}`
);
const json = (await response.json()) as {
stats: { total_subscribers: number };
};
const json = (await response.json()) as ConvertKitStats;

const { stats } = json;
const stats = json?.stats;
if (!stats) {
res.status(500).send({ message: 'Something went wrong' });
return;
return new Response(JSON.stringify({ message: 'Something went wrong' }), {
status: 500,
headers: {
'Content-Type': 'application/json',
},
});
}

const CACHE_TIME_IN_SECONDS = 60 * 5; // 5 minutes
res.setHeader('Cache-Control', `s-maxage=${CACHE_TIME_IN_SECONDS}`);
res.status(200).json({
subscriberCount: stats.total_subscribers,
});
const subscriberCountResponse = new Response(
JSON.stringify({ subscriberCount: stats.total_subscribers }),
{
headers: {
'Content-Type': 'application/json',
'Cache-Control': `s-maxage=${CACHE_TIME_IN_SECONDS}`,
},
}
);

return subscriberCountResponse;
}

export const config = {
runtime: 'edge',
};

0 comments on commit 7d33ce7

Please sign in to comment.