refactor(email): improve code formatting and error handling in email route

This commit is contained in:
2025-02-13 17:42:25 +01:00
parent efe2afb0b2
commit e610b9b462
5 changed files with 143 additions and 143 deletions

View File

@@ -1,4 +1,4 @@
import { type NextRequest, NextResponse } from "next/server"; import {type NextRequest, NextResponse} from "next/server";
import nodemailer from "nodemailer"; import nodemailer from "nodemailer";
import SMTPTransport from "nodemailer/lib/smtp-transport"; import SMTPTransport from "nodemailer/lib/smtp-transport";
import Mail from "nodemailer/lib/mailer"; import Mail from "nodemailer/lib/mailer";
@@ -7,63 +7,63 @@ import dotenv from "dotenv";
dotenv.config(); dotenv.config();
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
const body = (await request.json()) as { const body = (await request.json()) as {
email: string; email: string;
name: string; name: string;
message: string; message: string;
}; };
const { email, name, message } = body; const {email, name, message} = body;
const user = process.env.MY_EMAIL ?? ""; const user = process.env.MY_EMAIL ?? "";
const pass = process.env.MY_PASSWORD ?? ""; const pass = process.env.MY_PASSWORD ?? "";
if (!user || !pass) { if (!user || !pass) {
console.error("Missing email/password environment variables"); console.error("Missing email/password environment variables");
return NextResponse.json( return NextResponse.json(
{ error: "Internal server error" }, {error: "Internal server error"},
{ status: 500 }, {status: 500},
); );
} }
const transportOptions: SMTPTransport.Options = { const transportOptions: SMTPTransport.Options = {
host: "smtp.ionos.de", host: "smtp.ionos.de",
port: 587, port: 587,
secure: false, secure: false,
requireTLS: true, requireTLS: true,
auth: { auth: {
type: "login", type: "login",
user, user,
pass, pass,
}, },
}; };
const transport = nodemailer.createTransport(transportOptions); const transport = nodemailer.createTransport(transportOptions);
const mailOptions: Mail.Options = { const mailOptions: Mail.Options = {
from: user, from: user,
to: user, // Ensure this is the correct email address to: user, // Ensure this is the correct email address
subject: `Message from ${name} (${email})`, subject: `Message from ${name} (${email})`,
text: message + "\n\n" + email, text: message + "\n\n" + email,
}; };
const sendMailPromise = () => const sendMailPromise = () =>
new Promise<string>((resolve, reject) => { new Promise<string>((resolve, reject) => {
transport.sendMail(mailOptions, function (err, info) { transport.sendMail(mailOptions, function (err, info) {
if (!err) { if (!err) {
console.log("Email sent:", info.response); console.log("Email sent");
resolve(info.response); resolve(info.response);
} else { } else {
console.error("Error sending email:", err); console.error("Error sending email:", err);
reject(err.message); reject(err.message);
} }
}); });
}); });
try { try {
await sendMailPromise(); await sendMailPromise();
return NextResponse.json({ message: "Email sent" }); return NextResponse.json({message: "Email sent"});
} catch (err) { } catch (err) {
console.error("Error sending email:", err); console.error("Error sending email:", err);
return NextResponse.json({ error: err }, { status: 500 }); return NextResponse.json({error: err}, {status: 500});
} }
} }

View File

@@ -1,25 +1,26 @@
import { NextResponse } from "next/server"; import {NextResponse} from "next/server";
export const runtime = "nodejs"; // Force Node runtime export const runtime = "nodejs"; // Force Node runtime
const GHOST_API_URL = "http://big-bear-ghost:2368"; const GHOST_API_URL = "http://172.21.0.3:2368";
const GHOST_API_KEY = process.env.GHOST_API_KEY; const GHOST_API_KEY = process.env.GHOST_API_KEY;
export async function GET() { export async function GET() {
try { try {
const response = await fetch( const response = await fetch(
`${GHOST_API_URL}/ghost/api/content/posts/?key=${GHOST_API_KEY}&limit=all`, `${GHOST_API_URL}/ghost/api/content/posts/?key=${GHOST_API_KEY}&limit=all`,
); );
if (!response.ok) { if (!response.ok) {
throw new Error(`Failed to fetch posts: ${response.statusText}`); console.error(`Failed to fetch posts: ${response.statusText}`);
return NextResponse.json({});
}
const posts = await response.json();
return NextResponse.json(posts);
} catch (error) {
console.error("Failed to fetch posts from Ghost:", error);
return NextResponse.json(
{error: "Failed to fetch projects"},
{status: 500},
);
} }
const posts = await response.json();
return NextResponse.json(posts);
} catch (error) {
console.error("Failed to fetch posts from Ghost:", error);
return NextResponse.json(
{ error: "Failed to fetch projects" },
{ status: 500 },
);
}
} }

View File

@@ -11,7 +11,7 @@ interface ProjectsData {
export const runtime = "nodejs"; // Force Node runtime export const runtime = "nodejs"; // Force Node runtime
const GHOST_API_URL = "http://big-bear-ghost:2368"; const GHOST_API_URL = "http://172.21.0.3:2368";
const GHOST_API_KEY = process.env.GHOST_API_KEY; const GHOST_API_KEY = process.env.GHOST_API_KEY;
// Funktion, um die XML für die Sitemap zu generieren // Funktion, um die XML für die Sitemap zu generieren

View File

@@ -1,85 +1,84 @@
import React, { useEffect, useState } from "react"; import React, {useEffect, useState} from "react";
import Link from "next/link"; import Link from "next/link";
interface Project { interface Project {
slug: string; slug: string;
id: string; id: string;
title: string; title: string;
feature_image: string; feature_image: string;
visibility: string; visibility: string;
published_at: string; published_at: string;
updated_at: string; updated_at: string;
html: string; html: string;
reading_time: number; reading_time: number;
meta_description: string; meta_description: string;
} }
interface ProjectsData { interface ProjectsData {
posts: Project[]; posts: Project[];
} }
export default function Projects() { export default function Projects() {
const [projects, setProjects] = useState<Project[]>([]); const [projects, setProjects] = useState<Project[]>([]);
const [isVisible, setIsVisible] = useState(false); const [isVisible, setIsVisible] = useState(false);
useEffect(() => { useEffect(() => {
const fetchProjects = async () => { const fetchProjects = async () => {
try { try {
const response = await fetch("/api/fetchAllProjects"); const response = await fetch("/api/fetchAllProjects");
if (!response.ok) { if (!response.ok) {
throw new Error("Failed to fetch projects from Ghost"); console.error(`Failed to fetch projects: ${response.statusText}`);
} return [];
const projectsData = (await response.json()) as ProjectsData; }
setProjects(projectsData.posts); const projectsData = (await response.json()) as ProjectsData;
setProjects(projectsData.posts);
setTimeout(() => { setTimeout(() => {
setIsVisible(true); setIsVisible(true);
}, 250); // Delay to start the animation after Hero }, 250); // Delay to start the animation after Hero
} catch (error) { } catch (error) {
console.error("Failed to fetch projects:", error); console.error("Failed to fetch projects:", error);
} }
}; };
fetchProjects(); fetchProjects();
}, []); }, []);
console.log(projects.at(0)?.feature_image); const numberOfProjects = projects.length;
return (
const numberOfProjects = projects.length; <section
return ( id="projects"
<section className={`p-10 ${isVisible ? "animate-fly-in" : "opacity-0"}`}
id="projects"
className={`p-10 ${isVisible ? "animate-fly-in" : "opacity-0"}`}
>
<h2 className="text-3xl font-bold text-center text-gray-800">Projects</h2>
<div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
{projects.map((project, index) => (
<Link
key={project.id}
href={{
pathname: `/projects/${project.slug}`,
query: { project: JSON.stringify(project) },
}}
className="cursor-pointer"
>
<div
className={`p-4 border shadow-lg bg-white/45 rounded-2xl animate-fly-in`}
style={{ animationDelay: `${index * 0.1}s` }}
>
<h3 className="text-2xl font-bold text-gray-800">
{project.title}
</h3>
<p className="mt-2 text-gray-500">{project.meta_description}</p>
</div>
</Link>
))}
<div
className={`p-4 border shadow-lg bg-white/45 rounded-2xl animate-fly-in`}
style={{ animationDelay: `${(numberOfProjects + 1) * 0.1}s` }}
> >
<h3 className="text-2xl font-bold text-gray-800">More to come</h3> <h2 className="text-3xl font-bold text-center text-gray-800">Projects</h2>
<p className="mt-2 text-gray-500">...</p> <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
</div> {projects.map((project, index) => (
</div> <Link
</section> key={project.id}
); href={{
pathname: `/projects/${project.slug}`,
query: {project: JSON.stringify(project)},
}}
className="cursor-pointer"
>
<div
className={`p-4 border shadow-lg bg-white/45 rounded-2xl animate-fly-in`}
style={{animationDelay: `${index * 0.1}s`}}
>
<h3 className="text-2xl font-bold text-gray-800">
{project.title}
</h3>
<p className="mt-2 text-gray-500">{project.meta_description}</p>
</div>
</Link>
))}
<div
className={`p-4 border shadow-lg bg-white/45 rounded-2xl animate-fly-in`}
style={{animationDelay: `${(numberOfProjects + 1) * 0.1}s`}}
>
<h3 className="text-2xl font-bold text-gray-800">More to come</h3>
<p className="mt-2 text-gray-500">...</p>
</div>
</div>
</section>
);
} }

View File

@@ -59,7 +59,7 @@ const ProjectDetails = () => {
try { try {
fetchProjectData(slug); fetchProjectData(slug);
} catch (error) { } catch (error) {
console.log(error); console.error(error);
setError("Failed to fetch project data"); setError("Failed to fetch project data");
} }
} }