Add menu system built using MD

This commit is contained in:
Raven Scott
2024-09-26 18:13:47 -04:00
parent 56cb62bad7
commit 2d89dcddf6
7 changed files with 77 additions and 159 deletions

119
app.js
View File

@ -28,6 +28,31 @@ app.use(express.urlencoded({ extended: false }));
// Serve static files (CSS, Images)
app.use(express.static(path.join(__dirname, 'public')));
// Function to load menu items from the markdown file
function loadMenuItems() {
const menuFile = path.join(__dirname, 'menu.md');
const content = fs.readFileSync(menuFile, 'utf-8');
const menuItems = [];
const titleRegex = /<!--\s*title:\s*(.*?)\s*-->/g;
const urlRegex = /<!--\s*url:\s*(.*?)\s*-->/g;
let titleMatch;
let urlMatch;
while ((titleMatch = titleRegex.exec(content)) && (urlMatch = urlRegex.exec(content))) {
menuItems.push({
title: titleMatch[1],
url: urlMatch[1]
});
}
return menuItems;
}
// Load the menu once and make it available to all routes
const menuItems = loadMenuItems();
// Function to load and parse markdown files and extract lead
function loadMarkdownWithLead(file) {
const markdownContent = fs.readFileSync(path.join(__dirname, 'markdown', file), 'utf-8');
@ -54,11 +79,6 @@ function titleToSlug(title) {
.replace(/\s+/g, '-');
}
// Function to convert a slug back into a readable title
function slugToTitle(slug) {
return slug.replace(/-/g, ' ');
}
// Function to load all blog posts with pagination and search support
function getAllBlogPosts(page = 1, postsPerPage = 5, searchQuery = '') {
let blogFiles = fs.readdirSync(path.join(__dirname, 'markdown')).filter(file => file.endsWith('.md'));
@ -117,11 +137,11 @@ app.get('/', (req, res) => {
currentPage: page,
totalPages,
searchQuery, // Pass search query to the view
noResults // Pass this flag to indicate no results found
noResults, // Pass this flag to indicate no results found
menuItems // Pass the menu items to the view
});
});
// About Route (Load markdown and render using EJS)
app.get('/about', (req, res) => {
const aboutMarkdownFile = path.join(__dirname, 'me', 'about.md');
@ -136,72 +156,19 @@ app.get('/about', (req, res) => {
res.render('about', {
title: `About ${process.env.OWNER_NAME}`,
content: aboutContentHtml
content: aboutContentHtml,
menuItems // Pass the menu items to the view
});
});
});
// Display the Request a Quote form
// Contact Route (Render the contact form)
app.get('/contact', (req, res) => {
res.render('contact', { title: `Contact ${process.env.OWNER_NAME}`, msg: undefined });
});
// Handle contact form submission
app.post('/contact', async (req, res) => {
const { name, email, subject, message, 'g-recaptcha-response': captchaToken } = req.body;
if (!name || !email || !subject || !message) {
return res.render('contact', { title: `Contact ${process.env.OWNER_NAME}`, msg: 'All fields are required.' });
}
const captchaSecret = process.env.CAPTCHA_SECRET_KEY;
const captchaVerifyUrl = `https://www.google.com/recaptcha/api/siteverify?secret=${captchaSecret}&response=${captchaToken}`;
try {
const captchaResponse = await axios.post(captchaVerifyUrl);
if (!captchaResponse.data.success) {
return res.render('contact', { title: `Contact ${process.env.OWNER_NAME}`, msg: 'Captcha verification failed. Please try again.' });
}
const output = `
<p>You have a new contact request from <strong>${name}</strong>.</p>
<h3>Contact Details</h3>
<ul>
<li><strong>Name:</strong> ${name}</li>
<li><strong>Email:</strong> ${email}</li>
<li><strong>Subject:</strong> ${subject}</li>
</ul>
<h3>Message</h3>
<p>${message}</p>
`;
let transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
secure: false,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
tls: { rejectUnauthorized: false },
});
let mailOptions = {
from: `"${name}" <${process.env.RECEIVER_EMAIL}>`,
to: process.env.RECEIVER_EMAIL,
subject: subject,
html: output,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return res.render('contact', { title: `Contact ${process.env.OWNER_NAME}`, msg: 'An error occurred. Please try again.' });
}
return res.render('contact', { title: `Contact ${process.env.OWNER_NAME}`, msg: 'Your message has been sent successfully!' });
});
} catch (error) {
return res.render('contact', { title: `Contact ${process.env.OWNER_NAME}`, msg: 'An error occurred while verifying CAPTCHA. Please try again.' });
}
res.render('contact', {
title: `Contact ${process.env.OWNER_NAME}`,
msg: undefined,
menuItems // Pass the menu items to the view
});
});
// Blog Post Route
@ -223,14 +190,14 @@ app.get('/blog/:slug', (req, res) => {
content: contentHtml,
lead,
description, // Pass the description to the view
blogPosts
blogPosts,
menuItems // Pass the menu items to the view
});
} else {
res.redirect('/');
}
});
// Sitemap Route
app.get('/sitemap.xml', (req, res) => {
const hostname = req.headers.host || 'http://localhost';
@ -318,19 +285,9 @@ app.get('/rss', (req, res) => {
res.send(rssFeed);
});
// Create a URL object from the environment variable
const blog_URL = new URL(process.env.BLOG_URL);
// Extract just the hostname (e.g., blog.raven-scott.fyi)
const hostname = blog_URL.hostname;
// Global 404 handler for unmatched routes
app.use((req, res) => {
if (req.hostname === hostname) {
res.redirect(process.env.HOST_URL);
} else {
res.redirect('/');
}
res.redirect('/');
});
// Server Listening