refactor: improve news and email handling, style, folder structure (#16)

This commit is contained in:
Riccardo Senica
2024-06-04 18:04:54 +08:00
committed by GitHub
parent bc5e0cc195
commit acc10bf5fd
62 changed files with 1737 additions and 1553 deletions

View File

@@ -1,44 +1,61 @@
import { z } from 'zod';
import prisma from '../../../prisma/prisma';
import { ApiResponse } from '../../../utils/apiResponse';
import { ConfirmationSchema, ResponseSchema } from '../../../utils/schemas';
import prisma from '@prisma/prisma';
import { ApiResponse } from '@utils/apiResponse';
import {
BAD_REQUEST,
INTERNAL_SERVER_ERROR,
STATUS_BAD_REQUEST,
STATUS_INTERNAL_SERVER_ERROR,
STATUS_OK
} from '@utils/statusCodes';
import { ConfirmationSchema, ResponseType } from '@utils/validationSchemas';
import { Resend } from 'resend';
export const dynamic = 'force-dynamic'; // defaults to force-static
export async function POST(request: Request) {
const body = await request.json();
const validation = ConfirmationSchema.safeParse(body);
if (!validation.success || !validation.data.code) {
return ApiResponse(400, 'Bad request');
}
const user = await prisma.user.findUnique({
where: {
code: validation.data.code
try {
if (!process.env.RESEND_KEY || !process.env.RESEND_AUDIENCE) {
throw new Error('RESEND_AUDIENCE is not set');
}
const body = await request.json();
const validation = ConfirmationSchema.safeParse(body);
if (!validation.success || !validation.data.code) {
return ApiResponse(STATUS_BAD_REQUEST, BAD_REQUEST);
}
});
if (user) {
await prisma.user.update({
const user = await prisma.user.findUnique({
where: {
code: validation.data.code
},
data: {
confirmed: true
}
});
const message: z.infer<typeof ResponseSchema> = {
success: true,
message: `Thank you for confirming the subscription, ${user.email}!`
};
if (user) {
const resend = new Resend(process.env.RESEND_KEY);
return ApiResponse(200, JSON.stringify(message));
await resend.contacts.update({
id: user.resendId,
audienceId: process.env.RESEND_AUDIENCE,
unsubscribed: false
});
await prisma.user.update({
where: {
code: validation.data.code
},
data: {
confirmed: true
}
});
const message: ResponseType = {
success: true,
message: `Thank you for confirming the subscription, ${user.email}!`
};
return ApiResponse(STATUS_OK, message);
}
} catch (error) {
console.error(error);
return ApiResponse(STATUS_INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR);
}
const message: z.infer<typeof ResponseSchema> = {
success: false,
message: `It was not possible to confirm the subscription.`
};
return ApiResponse(200, JSON.stringify(message));
}

View File

@@ -1,50 +1,81 @@
import { NextResponse } from 'next/server';
import prisma from '../../../prisma/prisma';
import { NewsDatabaseSchema } from '../../../utils/schemas';
import { singleNews, topNews } from '../../../utils/urls';
import prisma from '@prisma/prisma';
import { ApiResponse } from '@utils/apiResponse';
import {
INTERNAL_SERVER_ERROR,
STATUS_INTERNAL_SERVER_ERROR,
STATUS_OK,
STATUS_UNAUTHORIZED
} from '@utils/statusCodes';
import { singleNews, topNews } from '@utils/urls';
import { NewsDatabaseSchema, NewsDatabaseType } from '@utils/validationSchemas';
import { Resend } from 'resend';
export async function GET(request: Request) {
if (
request.headers.get('Authorization') !== `Bearer ${process.env.CRON_SECRET}`
) {
return new Response('Unauthorized', { status: 401 });
return ApiResponse(STATUS_UNAUTHORIZED, 'Unauthorized');
}
try {
const topstories: number[] = await fetch(topNews).then(res => res.json());
const topStories: number[] = await fetch(topNews, {
cache: 'no-store'
}).then(res => res.json());
const newsPromises = topstories
.splice(0, Number(process.env.NEWS_LIMIT))
.map(async id => {
const sourceNews = await fetch(singleNews(id)).then(res => res.json());
const validation = NewsDatabaseSchema.safeParse(sourceNews);
console.info(`Top stories ids: ${topStories}`);
if (validation.success) {
const result = await prisma.news.upsert({
create: {
...validation.data,
id
},
update: {
...validation.data
},
where: {
id
}
});
const newsPromises = topStories
.slice(0, Number(process.env.NEWS_LIMIT))
.map(id => fetch(singleNews(id)).then(res => res.json()));
return result;
}
const news: NewsDatabaseType[] = await Promise.all(newsPromises);
const upsertPromises = news.map(async singleNews => {
const validation = NewsDatabaseSchema.safeParse(singleNews);
if (validation.success) {
console.info(
`Validated news N° ${singleNews.id} - ${singleNews.title}`
);
const result = await prisma.news.upsert({
create: {
...validation.data,
id: singleNews.id
},
update: {
...validation.data
},
where: {
id: singleNews.id
}
});
console.info(`Imported N° ${singleNews.id} - ${singleNews.title}`);
return result;
} else {
console.error(validation.error);
}
});
const result = await Promise.all(upsertPromises);
console.info(`Imported ${result.length} news.`);
if (process.env.ADMIN_EMAIL && process.env.RESEND_FROM) {
const resend = new Resend(process.env.RESEND_KEY);
await resend.emails.send({
from: process.env.RESEND_FROM,
to: [process.env.ADMIN_EMAIL],
subject: 'Newsletter: import cron job',
text: `Found these ids ${topStories.join(', ')} and imported ${result.length} of them.`
});
}
await Promise.all(newsPromises);
return new NextResponse(`Imported ${newsPromises.length} news.`, {
status: 200
});
} catch {
return new NextResponse(`Import failed.`, {
status: 500
});
return ApiResponse(STATUS_OK, `Imported ${newsPromises.length} news.`);
} catch (error) {
console.error(error);
return ApiResponse(STATUS_INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR);
}
}

View File

@@ -1,87 +1,114 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import NewsletterTemplate from '../../../components/emails/newsletter';
import prisma from '../../../prisma/prisma';
import { NewsSchema } from '../../../utils/schemas';
import { sender } from '../../../utils/sender';
import NewsletterTemplate from '@components/email/Newsletter';
import prisma from '@prisma/prisma';
import { ApiResponse } from '@utils/apiResponse';
import { sender } from '@utils/sender';
import {
INTERNAL_SERVER_ERROR,
STATUS_INTERNAL_SERVER_ERROR,
STATUS_OK,
STATUS_UNAUTHORIZED
} from '@utils/statusCodes';
import { Resend } from 'resend';
const ONE_DAY_IN_MS = 1000 * 60 * 60 * 24;
const TEN_MINUTES_IN_MS = 1000 * 10 * 60;
export async function GET(request: Request) {
if (
request.headers.get('Authorization') !== `Bearer ${process.env.CRON_SECRET}`
) {
return new Response('Unauthorized', { status: 401 });
return ApiResponse(STATUS_UNAUTHORIZED, 'Unauthorized');
}
// send newsletter to users who didn't get it in the last 23h 50m, assuming a cron job every 10 minutes
// this is to avoid sending the newsletter to the same users multiple times
// this is not a perfect solution, but it's good enough for now
const users = await prisma.user.findMany({
where: {
confirmed: true,
deleted: false,
OR: [
{
lastMail: {
lt: new Date(Date.now() - 1000 * 60 * 60 * 24 + 1000 * 10 * 60) // 24h - 10m
try {
// send newsletter to users who didn't get it in the last 23h 50m, assuming a cron job every 10 minutes
// this is to avoid sending the newsletter to the same users multiple times
// this is not a perfect solution, but it's good enough for now
const users = await prisma.user.findMany({
where: {
confirmed: true,
deleted: false,
OR: [
{
lastMail: {
lt: new Date(Date.now() - ONE_DAY_IN_MS + TEN_MINUTES_IN_MS) // 24h - 10m
}
},
{
lastMail: null
}
},
{
lastMail: null
]
},
select: {
id: true,
email: true
}
});
console.info(`Found ${users.length} users to mail to.`);
if (users.length === 0) {
return ApiResponse(STATUS_OK, 'No user to mail to.');
}
const news = await prisma.news.findMany({
where: {
createdAt: {
gt: new Date(Date.now() - ONE_DAY_IN_MS)
}
]
},
select: {
id: true,
email: true
}
});
if (users.length === 0) {
return new NextResponse('No users.', {
status: 200
},
orderBy: {
score: 'desc'
},
take: 25
});
}
const news = await prisma.news.findMany({
where: {
createdAt: {
gt: new Date(Date.now() - 1000 * 60 * 60 * 24)
}
},
orderBy: {
score: 'desc'
},
take: 25
});
console.info(`Found ${news.length} news to include in the newsletter.`);
const validRankedNews = news
.filter((item): item is z.infer<typeof NewsSchema> => item !== undefined)
.sort((a, b) => b.score - a.score);
if (process.env.ADMIN_EMAIL && process.env.RESEND_FROM) {
const resend = new Resend(process.env.RESEND_KEY);
const sent = await sender(
users.map(user => user.email),
NewsletterTemplate(validRankedNews)
);
if (!sent) {
return new NextResponse('Internal server error', {
status: 500
});
}
// update users so they don't get the newsletter again
await prisma.user.updateMany({
where: {
id: {
in: users.map(user => user.id)
}
},
data: {
lastMail: new Date()
await resend.emails.send({
from: process.env.RESEND_FROM,
to: [process.env.ADMIN_EMAIL],
subject: 'Newsletter: mailing cron job',
text: `Found ${users.length} users and ${news.length} news to send.`
});
}
});
return new NextResponse(`Newsletter sent to ${users.length} addresses.`, {
status: 200
});
if (news.length === 0) {
return ApiResponse(STATUS_OK, 'No news to include in newsletter.');
}
const validRankedNews = news.sort((a, b) => b.score - a.score);
const sent = await sender(
users.map(user => user.email),
NewsletterTemplate(validRankedNews)
);
if (!sent) {
return ApiResponse(STATUS_INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR);
}
// update users so they don't get the newsletter again
await prisma.user.updateMany({
where: {
id: {
in: users.map(user => user.id)
}
},
data: {
lastMail: new Date()
}
});
return ApiResponse(
STATUS_OK,
`Newsletter sent to ${users.length} addresses.`
);
} catch (error) {
console.error(error);
return ApiResponse(STATUS_INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR);
}
}

View File

@@ -1,22 +1,30 @@
import prisma from '../../../prisma/prisma';
import { ApiResponse } from '../../../utils/apiResponse';
import prisma from '@prisma/prisma';
import { ApiResponse } from '@utils/apiResponse';
import {
INTERNAL_SERVER_ERROR,
STATUS_INTERNAL_SERVER_ERROR,
STATUS_OK
} from '@utils/statusCodes';
export async function GET() {
const news = await prisma.news.findMany({
orderBy: {
createdAt: 'desc'
},
take: 50,
select: {
id: true,
title: true,
by: true
try {
const news = await prisma.news.findMany({
orderBy: {
createdAt: 'desc'
},
take: 50,
select: {
id: true,
title: true,
by: true
}
});
if (news) {
return ApiResponse(STATUS_OK, news);
}
});
if (news) {
return ApiResponse(200, JSON.stringify(news));
} catch (error) {
console.error(error);
return ApiResponse(STATUS_INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR);
}
return ApiResponse(500, 'Internal server error');
}

View File

@@ -1,76 +1,123 @@
import ConfirmationTemplate from '@components/email/Confirmation';
import prisma from '@prisma/prisma';
import { ApiResponse } from '@utils/apiResponse';
import { sender } from '@utils/sender';
import {
BAD_REQUEST,
INTERNAL_SERVER_ERROR,
STATUS_BAD_REQUEST,
STATUS_INTERNAL_SERVER_ERROR,
STATUS_OK
} from '@utils/statusCodes';
import { ResponseType, SubscribeFormSchema } from '@utils/validationSchemas';
import * as crypto from 'crypto';
import { z } from 'zod';
import ConfirmationTemplate from '../../../components/emails/confirmation';
import prisma from '../../../prisma/prisma';
import { ApiResponse } from '../../../utils/apiResponse';
import { ResponseSchema, SubscribeFormSchema } from '../../../utils/schemas';
import { sender } from '../../../utils/sender';
import { Resend } from 'resend';
export const dynamic = 'force-dynamic'; // defaults to force-static
export async function POST(request: Request) {
const body = await request.json();
const validation = SubscribeFormSchema.safeParse(body);
if (!validation.success) {
return ApiResponse(400, 'Bad request');
}
const { email } = validation.data;
const userAlreadyConfirmed = await prisma.user.findUnique({
where: {
email,
confirmed: true
try {
if (!process.env.RESEND_KEY || !process.env.RESEND_AUDIENCE) {
throw new Error('RESEND_KEY is not set');
}
});
if (userAlreadyConfirmed) {
if (userAlreadyConfirmed.deleted) {
const body = await request.json();
const validation = SubscribeFormSchema.safeParse(body);
if (!validation.success) {
return ApiResponse(STATUS_BAD_REQUEST, BAD_REQUEST);
}
const { email } = validation.data;
const user = await prisma.user.findUnique({
where: {
email
}
});
const resend = new Resend(process.env.RESEND_KEY);
const code = crypto
.createHash('sha256')
.update(`${process.env.SECRET_HASH}${email}}`)
.digest('hex');
if (user && user.confirmed) {
if (user.deleted) {
await prisma.user.update({
where: {
email
},
data: {
deleted: false
}
});
const contact = await resend.contacts.get({
id: user.resendId,
audienceId: process.env.RESEND_AUDIENCE
});
if (!contact) {
await resend.contacts.update({
id: user.resendId,
audienceId: process.env.RESEND_AUDIENCE,
unsubscribed: true
});
}
}
const message: ResponseType = {
success: true,
message: `Thank you for subscribing!`
};
return ApiResponse(STATUS_OK, message);
} else if (user && !user.confirmed) {
await prisma.user.update({
where: {
email
},
data: {
deleted: false
code
}
});
} else {
const contact = await resend.contacts.create({
email: email,
audienceId: process.env.RESEND_AUDIENCE,
unsubscribed: true
});
if (!contact.data?.id) {
throw new Error('Failed to create Resend contact');
}
await prisma.user.create({
data: {
email,
code,
resendId: contact.data.id
}
});
}
const message: z.infer<typeof ResponseSchema> = {
const sent = await sender([email], ConfirmationTemplate(code));
if (!sent) {
return ApiResponse(STATUS_INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR);
}
const message: ResponseType = {
success: true,
message: `Thank you for subscribing!`
message: `Thank you! You will now receive an email to ${email} to confirm the subscription.`
};
return ApiResponse(200, JSON.stringify(message));
return ApiResponse(STATUS_OK, message);
} catch (error) {
console.error(error);
return ApiResponse(STATUS_INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR);
}
const code = crypto
.createHash('sha256')
.update(`${process.env.SECRET_HASH}${email}}`)
.digest('hex');
await prisma.user.upsert({
create: {
email,
code
},
update: {
code
},
where: {
email
}
});
const sent = await sender([email], ConfirmationTemplate(code));
if (!sent) {
return ApiResponse(500, 'Internal server error');
}
const message: z.infer<typeof ResponseSchema> = {
success: true,
message: `Thank you! You will now receive an email to ${email} to confirm the subscription.`
};
return ApiResponse(200, JSON.stringify(message));
}

View File

@@ -1,47 +1,74 @@
import { z } from 'zod';
import UnsubscribeTemplate from '../../../components/emails/unsubscribe';
import prisma from '../../../prisma/prisma';
import { ApiResponse } from '../../../utils/apiResponse';
import { ResponseSchema, UnsubscribeFormSchema } from '../../../utils/schemas';
import { sender } from '../../../utils/sender';
import UnsubscribeTemplate from '@components/email/Unsubscribe';
import prisma from '@prisma/prisma';
import { ApiResponse } from '@utils/apiResponse';
import { sender } from '@utils/sender';
import {
BAD_REQUEST,
INTERNAL_SERVER_ERROR,
STATUS_BAD_REQUEST,
STATUS_INTERNAL_SERVER_ERROR,
STATUS_OK
} from '@utils/statusCodes';
import { ResponseType, UnsubscribeFormSchema } from '@utils/validationSchemas';
import { Resend } from 'resend';
export const dynamic = 'force-dynamic'; // defaults to force-static
export async function POST(request: Request) {
const body = await request.json();
const validation = UnsubscribeFormSchema.safeParse(body);
if (!validation.success) {
return ApiResponse(400, 'Bad request');
}
const { email } = validation.data;
const user = await prisma.user.findUnique({
where: {
email
try {
if (!process.env.RESEND_KEY || !process.env.RESEND_AUDIENCE) {
throw new Error('RESEND_AUDIENCE is not set');
}
const body = await request.json();
const validation = UnsubscribeFormSchema.safeParse(body);
if (!validation.success) {
return ApiResponse(STATUS_BAD_REQUEST, BAD_REQUEST);
}
});
if (user && !user.deleted) {
await prisma.user.update({
const { email } = validation.data;
const user = await prisma.user.findUnique({
where: {
email
},
data: {
deleted: true
}
});
const sent = await sender([email], UnsubscribeTemplate());
if (user && !user.deleted) {
await prisma.user.update({
where: {
email
},
data: {
deleted: true
}
});
if (!sent) {
return ApiResponse(500, 'Internal server error');
const resend = new Resend(process.env.RESEND_KEY);
await resend.contacts.update({
id: user.resendId,
audienceId: process.env.RESEND_AUDIENCE,
unsubscribed: true
});
const sent = await sender([email], UnsubscribeTemplate());
if (!sent) {
return ApiResponse(
STATUS_INTERNAL_SERVER_ERROR,
'Internal server error'
);
}
}
const message: ResponseType = {
success: true,
message: `${email} unsubscribed.`
};
return ApiResponse(STATUS_OK, message);
} catch (error) {
console.error(error);
return ApiResponse(STATUS_INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR);
}
const message: z.infer<typeof ResponseSchema> = {
success: true,
message: `${email} unsubscribed.`
};
return ApiResponse(200, JSON.stringify(message));
}