Merge pull request 'feat: redirect if page is below 1' (#1) from Cyber/ravenscott-blog:main into main

Reviewed-on: snxraven/ravenscott-blog#1
This commit is contained in:
snxraven 2024-09-16 16:03:46 -04:00
commit 0c9279805e

15
app.js
View File

@ -31,7 +31,7 @@ app.use(express.static(path.join(__dirname, 'public')));
// Function to load and parse markdown files and extract lead
function loadMarkdownWithLead(file) {
const markdownContent = fs.readFileSync(path.join(__dirname, 'markdown', file), 'utf-8');
let lead = '';
let contentMarkdown = markdownContent;
@ -74,7 +74,7 @@ function getAllBlogPosts(page = 1, postsPerPage = 5) {
const end = start + postsPerPage;
const paginatedFiles = blogFiles.slice(start, end);
const blogPosts = paginatedFiles.map(file => {
const title = file.replace('.md', '').replace(/-/g, ' '); // Keep original casing for title
const slug = titleToSlug(title); // Convert title to slug (lowercase)
@ -82,7 +82,7 @@ function getAllBlogPosts(page = 1, postsPerPage = 5) {
// Get the last modified date of the markdown file
const stats = fs.statSync(path.join(__dirname, 'markdown', file));
const lastModifiedDate = new Date(stats.mtime); // Use mtime for last modification time
// Format the date
const formattedDate = lastModifiedDate.toLocaleDateString('en-US', {
year: 'numeric',
@ -103,10 +103,15 @@ function getAllBlogPosts(page = 1, postsPerPage = 5) {
// Home Route (Blog Home with Pagination)
app.get('/', (req, res) => {
const page = parseInt(req.query.page) || 1;
if (page < 1) {
return res.redirect(req.hostname);
}
const postsPerPage = 5; // Set how many posts to display per page
const { blogPosts, totalPages } = getAllBlogPosts(page, postsPerPage);
res.render('index', {
title: 'Raven Scott Blog',
blogPosts,
@ -185,7 +190,7 @@ app.post('/contact', (req, res) => {
app.get('/blog/:slug', (req, res) => {
const slug = req.params.slug;
const markdownFile = fs.readdirSync(path.join(__dirname, 'markdown'))
.find(file => titleToSlug(file.replace('.md', '')) === slug);
.find(file => titleToSlug(file.replace('.md', '')) === slug);
if (markdownFile) {
const originalTitle = markdownFile.replace('.md', ''); // Original title with casing