refactor: improve news and email handling, style, folder structure (#16)
This commit is contained in:
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
'use client';
|
||||
import { CardDescription } from '@components/Card';
|
||||
import CustomCard from '@components/CustomCard';
|
||||
import { ResponseType } from '@utils/validationSchemas';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { Suspense, useEffect, useState } from 'react';
|
||||
import { z } from 'zod';
|
||||
import { Card } from '../../components/custom/card';
|
||||
import { ResponseSchema } from '../../utils/schemas';
|
||||
|
||||
function ConfirmationPage() {
|
||||
const router = useRouter();
|
||||
@@ -14,49 +14,59 @@ function ConfirmationPage() {
|
||||
const code = searchParams.get('code');
|
||||
|
||||
useEffect(() => {
|
||||
if (!code) {
|
||||
router.push('/');
|
||||
}
|
||||
const fetchData = async () => {
|
||||
if (!code) {
|
||||
router.push('/');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/confirmation', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
code: code
|
||||
})
|
||||
});
|
||||
|
||||
fetch('/api/confirmation', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
code: code
|
||||
})
|
||||
})
|
||||
.then(async res => {
|
||||
if (!res.ok) {
|
||||
router.push('/');
|
||||
return;
|
||||
}
|
||||
|
||||
const response: z.infer<typeof ResponseSchema> = await res.json();
|
||||
const response: ResponseType = await res.json();
|
||||
|
||||
if (!response.success) {
|
||||
router.push('/');
|
||||
return;
|
||||
}
|
||||
|
||||
return response;
|
||||
})
|
||||
.then(response => {
|
||||
setMessage(response.message);
|
||||
setLoading(false);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
router.push('/');
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, [code, router]);
|
||||
|
||||
function render() {
|
||||
if (!loading) {
|
||||
return message;
|
||||
return (
|
||||
<CardDescription className='text-center'>{message}</CardDescription>
|
||||
);
|
||||
}
|
||||
|
||||
return 'Just a second...';
|
||||
}
|
||||
|
||||
return (
|
||||
<Card
|
||||
style='text-center'
|
||||
<CustomCard
|
||||
className='max-90vw w-96'
|
||||
title={loading ? 'Verifying' : 'Confirmed!'}
|
||||
content={render()}
|
||||
footer={false}
|
||||
@@ -66,7 +76,7 @@ function ConfirmationPage() {
|
||||
|
||||
export default function Confirmation() {
|
||||
return (
|
||||
<Suspense>
|
||||
<Suspense fallback={<>Loading...</>}>
|
||||
<ConfirmationPage />
|
||||
</Suspense>
|
||||
);
|
||||
|
||||
@@ -35,47 +35,25 @@
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: 0 0% 3.9%;
|
||||
--foreground: 0 0% 98%;
|
||||
|
||||
--card: 0 0% 3.9%;
|
||||
--card-foreground: 0 0% 98%;
|
||||
|
||||
--popover: 0 0% 3.9%;
|
||||
--popover-foreground: 0 0% 98%;
|
||||
|
||||
--primary: 0 0% 98%;
|
||||
--primary-foreground: 0 0% 9%;
|
||||
|
||||
--secondary: 0 0% 14.9%;
|
||||
--secondary-foreground: 0 0% 98%;
|
||||
|
||||
--muted: 0 0% 14.9%;
|
||||
--muted-foreground: 0 0% 63.9%;
|
||||
|
||||
--accent: 0 0% 14.9%;
|
||||
--accent-foreground: 0 0% 98%;
|
||||
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
|
||||
--border: 0 0% 14.9%;
|
||||
--input: 0 0% 14.9%;
|
||||
--ring: 0 0% 83.1%;
|
||||
h1 {
|
||||
@apply text-3xl font-semibold;
|
||||
}
|
||||
}
|
||||
|
||||
.styledH2 {
|
||||
@apply text-xl font-bold;
|
||||
}
|
||||
h2 {
|
||||
@apply text-2xl font-semibold;
|
||||
}
|
||||
|
||||
.styledH3 {
|
||||
@apply text-lg font-semibold;
|
||||
}
|
||||
h3 {
|
||||
@apply text-xl font-semibold;
|
||||
}
|
||||
|
||||
.styledH4 {
|
||||
@apply text-base font-medium;
|
||||
h4 {
|
||||
@apply text-lg font-semibold;
|
||||
}
|
||||
|
||||
h6 {
|
||||
@apply text-lg italic;
|
||||
}
|
||||
}
|
||||
|
||||
/* Card border gradient */
|
||||
@@ -102,7 +80,6 @@ body {
|
||||
content: '';
|
||||
top: calc(-1 * var(--radius));
|
||||
left: calc(-1 * var(--radius));
|
||||
z-index: -1;
|
||||
width: calc(100% + var(--radius) * 2);
|
||||
height: calc(100% + var(--radius) * 2);
|
||||
background: linear-gradient(
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import Tiles from '@components/tiles/Tiles';
|
||||
import { cn } from '@utils/ui';
|
||||
import { Analytics } from '@vercel/analytics/react';
|
||||
import type { Metadata } from 'next';
|
||||
import { Inter as FontSans } from 'next/font/google';
|
||||
import { Tiles } from '../components/custom/tiles/tiles';
|
||||
import { cn } from '../utils/ui';
|
||||
import './globals.css';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
@@ -22,16 +22,16 @@ export default function RootLayout({
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html lang='en' suppressHydrationWarning>
|
||||
<html lang='en'>
|
||||
<head />
|
||||
<body
|
||||
className={cn(
|
||||
'flex min-h-screen items-center justify-center bg-background font-sans antialiased',
|
||||
'flex justify-center bg-background font-sans antialiased',
|
||||
fontSans.variable
|
||||
)}
|
||||
>
|
||||
<Tiles>
|
||||
<div style={{ zIndex: 2 }}>{children}</div>
|
||||
<div className='z-10'>{children}</div>
|
||||
</Tiles>
|
||||
<Analytics />
|
||||
</body>
|
||||
|
||||
64
app/page.tsx
64
app/page.tsx
@@ -1,46 +1,35 @@
|
||||
'use client';
|
||||
import { Button } from '@components/Button';
|
||||
import { CardDescription } from '@components/Card';
|
||||
import CustomCard from '@components/CustomCard';
|
||||
import ErrorMessage from '@components/ErrorMessage';
|
||||
import { FormControl } from '@components/form/FormControl';
|
||||
import { FormMessage } from '@components/form/FormMessage';
|
||||
import { Input } from '@components/Input';
|
||||
import { FormField } from '@contexts/FormField/FormFieldProvider';
|
||||
import { FormItem } from '@contexts/FormItem/FormItemProvider';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import { Card } from '../components/custom/card';
|
||||
import ErrorMessage from '../components/custom/error';
|
||||
import { Button } from '../components/ui/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormMessage
|
||||
} from '../components/ui/form';
|
||||
import { Input } from '../components/ui/input';
|
||||
import { ResponseSchema, SubscribeFormSchema } from '../utils/schemas';
|
||||
ResponseType,
|
||||
SubscribeFormSchema,
|
||||
SubscribeFormType
|
||||
} from '@utils/validationSchemas';
|
||||
import { useState } from 'react';
|
||||
import { FormProvider, useForm } from 'react-hook-form';
|
||||
|
||||
export default function Home() {
|
||||
const [completed, setCompleted] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [error, setError] = useState(false);
|
||||
const honeypotRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
const form = useForm<z.infer<typeof SubscribeFormSchema>>({
|
||||
const form = useForm<SubscribeFormType>({
|
||||
resolver: zodResolver(SubscribeFormSchema),
|
||||
defaultValues: {
|
||||
email: '',
|
||||
name: ''
|
||||
email: ''
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (honeypotRef.current) {
|
||||
honeypotRef.current.style.display = 'none';
|
||||
}
|
||||
}, []);
|
||||
|
||||
async function handleSubmit(values: z.infer<typeof SubscribeFormSchema>) {
|
||||
if (values.name) {
|
||||
return;
|
||||
}
|
||||
|
||||
async function handleSubmit(values: SubscribeFormType) {
|
||||
try {
|
||||
const response = await fetch('/api/subscribe', {
|
||||
method: 'POST',
|
||||
@@ -56,8 +45,7 @@ export default function Home() {
|
||||
throw new Error(`Invalid response: ${response.status}`);
|
||||
}
|
||||
|
||||
const formResponse: z.infer<typeof ResponseSchema> =
|
||||
await response.json();
|
||||
const formResponse: ResponseType = await response.json();
|
||||
|
||||
if (!formResponse.success) {
|
||||
throw Error(formResponse.message);
|
||||
@@ -76,12 +64,14 @@ export default function Home() {
|
||||
}
|
||||
|
||||
if (completed) {
|
||||
return message;
|
||||
return (
|
||||
<CardDescription className='text-center'>{message}</CardDescription>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='mx-2 h-44'>
|
||||
<Form {...form}>
|
||||
<FormProvider {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(handleSubmit)}
|
||||
className='flex flex-col space-y-4'
|
||||
@@ -91,7 +81,7 @@ export default function Home() {
|
||||
name='email'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<div className='h-4'>
|
||||
<div className='h-6'>
|
||||
<FormMessage className='text-center' />
|
||||
</div>
|
||||
<FormControl>
|
||||
@@ -108,7 +98,7 @@ export default function Home() {
|
||||
<Button type='submit'>Submit</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</FormProvider>
|
||||
<p className='py-1 text-center text-xs text-gray-600'>
|
||||
You can rest assured that we will fill your inbox with spam. We
|
||||
don't like it either! 🙂
|
||||
@@ -118,8 +108,8 @@ export default function Home() {
|
||||
}
|
||||
|
||||
return (
|
||||
<Card
|
||||
style='text-center max-w-96'
|
||||
<CustomCard
|
||||
className='max-90vw w-96'
|
||||
title='Interested in keeping up with the latest from the tech world? 👩💻'
|
||||
description='Subscribe to our newsletter! The top stories from Hackernews for you. Once a day. Every day.'
|
||||
content={render()}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import CustomCard from '@components/CustomCard';
|
||||
import Link from 'next/link';
|
||||
import { Card } from '../../components/custom/card';
|
||||
|
||||
export default function Privacy() {
|
||||
const body = (
|
||||
@@ -25,8 +26,8 @@ export default function Privacy() {
|
||||
.
|
||||
</p>
|
||||
<br />
|
||||
<h2 className='styledH2'>Interpretation and Definitions</h2>
|
||||
<h3 className='styledH3'>Interpretation</h3>
|
||||
<h2>Interpretation and Definitions</h2>
|
||||
<h3>Interpretation</h3>
|
||||
<p>
|
||||
The words of which the initial letter is capitalized have meanings
|
||||
defined under the following conditions. The following definitions shall
|
||||
@@ -34,7 +35,7 @@ export default function Privacy() {
|
||||
in plural.
|
||||
</p>
|
||||
<br />
|
||||
<h3 className='styledH3'>Definitions</h3>
|
||||
<h4>Definitions</h4>
|
||||
<p>For the purposes of this Privacy Policy:</p>
|
||||
<ul>
|
||||
<li>
|
||||
@@ -115,9 +116,9 @@ export default function Privacy() {
|
||||
</li>
|
||||
</ul>
|
||||
<br />
|
||||
<h2 className='styledH2'>Collecting and Using Your Personal Data</h2>
|
||||
<h3 className='styledH3'>Types of Data Collected</h3>
|
||||
<h4 className='styledH4'>Personal Data</h4>
|
||||
<h3>Collecting and Using Your Personal Data</h3>
|
||||
<h4>Types of Data Collected</h4>
|
||||
<h6>Personal Data</h6>
|
||||
<p>
|
||||
While using Our Service, We may ask You to provide Us with certain
|
||||
personally identifiable information that can be used to contact or
|
||||
@@ -133,7 +134,7 @@ export default function Privacy() {
|
||||
</li>
|
||||
</ul>
|
||||
<br />
|
||||
<h4 className='styledH4'>Usage Data</h4>
|
||||
<h6>Usage Data</h6>
|
||||
<p>Usage Data is collected automatically when using the Service.</p>
|
||||
<p>
|
||||
Usage Data may include information such as Your Device&aposs Internet
|
||||
@@ -156,7 +157,7 @@ export default function Privacy() {
|
||||
device.
|
||||
</p>
|
||||
<br />
|
||||
<h3 className='styledH3'>Use of Your Personal Data</h3>
|
||||
<h4>Use of Your Personal Data</h4>
|
||||
<p>The Company may use Personal Data for the following purposes:</p>
|
||||
<ul>
|
||||
<li>
|
||||
@@ -265,7 +266,7 @@ export default function Privacy() {
|
||||
</li>
|
||||
</ul>
|
||||
<br />
|
||||
<h3 className='styledH3'>Retention of Your Personal Data</h3>
|
||||
<h4>Retention of Your Personal Data</h4>
|
||||
<p>
|
||||
The Company will retain Your Personal Data only for as long as is
|
||||
necessary for the purposes set out in this Privacy Policy. We will
|
||||
@@ -282,7 +283,7 @@ export default function Privacy() {
|
||||
data for longer time periods.
|
||||
</p>
|
||||
<br />
|
||||
<h3 className='styledH3'>Transfer of Your Personal Data</h3>
|
||||
<h4>Transfer of Your Personal Data</h4>
|
||||
<p>
|
||||
Your information, including Personal Data, is processed at the
|
||||
Company&aposs operating offices and in any other places where the
|
||||
@@ -304,7 +305,7 @@ export default function Privacy() {
|
||||
security of Your data and other personal information.
|
||||
</p>
|
||||
<br />
|
||||
<h3 className='styledH3'>Delete Your Personal Data</h3>
|
||||
<h4>Delete Your Personal Data</h4>
|
||||
<p>
|
||||
You have the right to delete or request that We assist in deleting the
|
||||
Personal Data that We have collected about You.
|
||||
@@ -325,8 +326,8 @@ export default function Privacy() {
|
||||
when we have a legal obligation or lawful basis to do so.
|
||||
</p>
|
||||
<br />
|
||||
<h3 className='styledH3'>Disclosure of Your Personal Data</h3>
|
||||
<h4 className='styledH4'>Business Transactions</h4>
|
||||
<h4>Disclosure of Your Personal Data</h4>
|
||||
<h6>Business Transactions</h6>
|
||||
<p>
|
||||
If the Company is involved in a merger, acquisition or asset sale, Your
|
||||
Personal Data may be transferred. We will provide notice before Your
|
||||
@@ -334,14 +335,14 @@ export default function Privacy() {
|
||||
Policy.
|
||||
</p>
|
||||
<br />
|
||||
<h4 className='styledH4'>Law enforcement</h4>
|
||||
<h6>Law enforcement</h6>
|
||||
<p>
|
||||
Under certain circumstances, the Company may be required to disclose
|
||||
Your Personal Data if required to do so by law or in response to valid
|
||||
requests by public authorities (e.g. a court or a government agency).
|
||||
</p>
|
||||
<br />
|
||||
<h4 className='styledH4'>Other legal requirements</h4>
|
||||
<h6>Other legal requirements</h6>
|
||||
<p>
|
||||
The Company may disclose Your Personal Data in the good faith belief
|
||||
that such action is necessary to:
|
||||
@@ -358,9 +359,8 @@ export default function Privacy() {
|
||||
</li>
|
||||
<li>Protect against legal liability</li>
|
||||
</ul>
|
||||
|
||||
<br />
|
||||
<h3 className='styledH3'>Security of Your Personal Data</h3>
|
||||
<h4>Security of Your Personal Data</h4>
|
||||
<p>
|
||||
The security of Your Personal Data is important to Us, but remember that
|
||||
no method of transmission over the Internet, or method of electronic
|
||||
@@ -369,7 +369,7 @@ export default function Privacy() {
|
||||
security.
|
||||
</p>
|
||||
<br />
|
||||
<h2 className='styledH2'>{"Children's Privacy"}</h2>
|
||||
<h3>{"Children's Privacy"}</h3>
|
||||
<p>
|
||||
Our Service does not address anyone under the age of 13. We do not
|
||||
knowingly collect personally identifiable information from anyone under
|
||||
@@ -386,7 +386,7 @@ export default function Privacy() {
|
||||
information.
|
||||
</p>
|
||||
<br />
|
||||
<h2 className='styledH2'>Links to Other Websites</h2>
|
||||
<h3>Links to Other Websites</h3>
|
||||
<p>
|
||||
Our Service may contain links to other websites that are not operated by
|
||||
Us. If You click on a third party link, You will be directed to that
|
||||
@@ -398,7 +398,7 @@ export default function Privacy() {
|
||||
privacy policies or practices of any third party sites or services.
|
||||
</p>
|
||||
<br />
|
||||
<h2 className='styledH2'>Changes to this Privacy Policy</h2>
|
||||
<h3>Changes to this Privacy Policy</h3>
|
||||
<p>
|
||||
We may update Our Privacy Policy from time to time. We will notify You
|
||||
of any changes by posting the new Privacy Policy on this page.
|
||||
@@ -414,7 +414,7 @@ export default function Privacy() {
|
||||
posted on this page.
|
||||
</p>
|
||||
<br />
|
||||
<h2 className='styledH2'>Contact Us</h2>
|
||||
<h3>Contact Us</h3>
|
||||
<p>
|
||||
If you have any questions about this Privacy Policy, You can contact us
|
||||
by writing to{' '}
|
||||
@@ -439,8 +439,8 @@ export default function Privacy() {
|
||||
);
|
||||
|
||||
return (
|
||||
<Card
|
||||
style='max-h-[90vh] max-w-[90vw]'
|
||||
<CustomCard
|
||||
className='max-90vh max-90vw'
|
||||
title='Privacy Policy'
|
||||
description='Last updated: December 03, 2023'
|
||||
content={body}
|
||||
|
||||
@@ -4,7 +4,7 @@ export default function robots(): MetadataRoute.Robots {
|
||||
return {
|
||||
rules: {
|
||||
userAgent: '*',
|
||||
disallow: '/'
|
||||
disallow: ''
|
||||
},
|
||||
sitemap: `${process.env.HOME_URL!}/sitemap.xml`
|
||||
};
|
||||
|
||||
@@ -1,46 +1,42 @@
|
||||
'use client';
|
||||
import { Button } from '@components/Button';
|
||||
import { CardDescription } from '@components/Card';
|
||||
import CustomCard from '@components/CustomCard';
|
||||
import ErrorMessage from '@components/ErrorMessage';
|
||||
import { FormControl } from '@components/form/FormControl';
|
||||
import { FormMessage } from '@components/form/FormMessage';
|
||||
import { Input } from '@components/Input';
|
||||
import { FormField } from '@contexts/FormField/FormFieldProvider';
|
||||
import { FormItem } from '@contexts/FormItem/FormItemProvider';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import { Card } from '../../components/custom/card';
|
||||
import ErrorMessage from '../../components/custom/error';
|
||||
import { Button } from '../../components/ui/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormMessage
|
||||
} from '../../components/ui/form';
|
||||
import { Input } from '../../components/ui/input';
|
||||
import { ResponseSchema, UnsubscribeFormSchema } from '../../utils/schemas';
|
||||
ResponseType,
|
||||
UnsubscribeFormSchema,
|
||||
UnsubscribeFormType
|
||||
} from '@utils/validationSchemas';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { FormProvider, useForm } from 'react-hook-form';
|
||||
|
||||
export default function Unsubscribe() {
|
||||
const [completed, setCompleted] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [error, setError] = useState(false);
|
||||
const honeypotRef = useRef<HTMLInputElement | null>(null);
|
||||
const ref = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
const form = useForm<z.infer<typeof UnsubscribeFormSchema>>({
|
||||
const form = useForm<UnsubscribeFormType>({
|
||||
resolver: zodResolver(UnsubscribeFormSchema),
|
||||
defaultValues: {
|
||||
email: '',
|
||||
name: ''
|
||||
email: ''
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (honeypotRef.current) {
|
||||
honeypotRef.current.style.display = 'none';
|
||||
if (ref.current) {
|
||||
ref.current.style.display = 'none';
|
||||
}
|
||||
}, []);
|
||||
|
||||
async function handleSubmit(values: z.infer<typeof UnsubscribeFormSchema>) {
|
||||
if (values.name) {
|
||||
return;
|
||||
}
|
||||
|
||||
async function handleSubmit(values: UnsubscribeFormType) {
|
||||
try {
|
||||
const response = await fetch('/api/unsubscribe', {
|
||||
method: 'POST',
|
||||
@@ -56,8 +52,7 @@ export default function Unsubscribe() {
|
||||
throw new Error(`Invalid response: ${response.status}`);
|
||||
}
|
||||
|
||||
const formResponse: z.infer<typeof ResponseSchema> =
|
||||
await response.json();
|
||||
const formResponse: ResponseType = await response.json();
|
||||
|
||||
if (!formResponse.success) {
|
||||
throw Error(formResponse.message);
|
||||
@@ -76,12 +71,14 @@ export default function Unsubscribe() {
|
||||
}
|
||||
|
||||
if (completed) {
|
||||
return message;
|
||||
return (
|
||||
<CardDescription className='text-center'>{message}</CardDescription>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='mb-5 h-32'>
|
||||
<Form {...form}>
|
||||
<FormProvider {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(handleSubmit)}
|
||||
className='flex flex-col space-y-4'
|
||||
@@ -91,11 +88,15 @@ export default function Unsubscribe() {
|
||||
name='email'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<div className='h-4'>
|
||||
<div className='h-6'>
|
||||
<FormMessage className='text-center' />
|
||||
</div>
|
||||
<FormControl>
|
||||
<Input placeholder='example@example.com' {...field} />
|
||||
<Input
|
||||
placeholder='example@example.com'
|
||||
className='text-center'
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
@@ -104,14 +105,14 @@ export default function Unsubscribe() {
|
||||
<Button type='submit'>Submit</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</FormProvider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card
|
||||
style='text-center max-w-80'
|
||||
<CustomCard
|
||||
className='max-90vw w-96'
|
||||
title='Unsubscribe'
|
||||
description='You sure you want to leave? :('
|
||||
content={render()}
|
||||
|
||||
Reference in New Issue
Block a user