Browse Source

Merge pull request #34 from jrtechs/NextPage

Next page implementation
pull/39/head
Jeffery Russell 6 years ago
committed by GitHub
parent
commit
d67c0ddc09
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 173 additions and 87 deletions
  1. +2
    -2
      includes/html/header.html
  2. +1
    -1
      includes/includes.js
  3. +5
    -2
      includes/staticContentServer.js
  4. +13
    -34
      posts/category.js
  5. +5
    -27
      posts/homePage.js
  6. +5
    -11
      posts/posts.js
  7. +55
    -0
      posts/renderBatchOfPreviewes.js
  8. +66
    -0
      posts/renderNextBar.js
  9. +20
    -6
      sites/blog.js
  10. +0
    -3
      sites/projects.js
  11. +1
    -1
      utils/sql.js

+ 2
- 2
includes/html/header.html View File

@ -8,8 +8,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/includes/css/purge.css" media="screen">
<!--<link rel="stylesheet" href="/css/bootstrap.css" media="screen">-->
<!--<link rel="stylesheet" href="/includes/css/purge.css" media="screen">-->
<link rel="stylesheet" href="/includes/css/bootstrap.css" media="screen">
<link rel="stylesheet" href="/includes/css/code.css" media="screen"> <link rel="stylesheet" href="/includes/css/code.css" media="screen">

+ 1
- 1
includes/includes.js View File

@ -50,9 +50,9 @@ const sendCachedContent = function(path, type, result)
'Vary': 'Accept-Encoding'}); 'Vary': 'Accept-Encoding'});
result.write(content); result.write(content);
result.end(); result.end();
cache.put(path, content);
}).catch(function(error) }).catch(function(error)
{ {
cache.del(path);
console.log(error); console.log(error);
}); });
} }

+ 5
- 2
includes/staticContentServer.js View File

@ -35,8 +35,11 @@ module.exports=
//scripts //scripts
else if (filename.includes(".js")) else if (filename.includes(".js"))
{ {
includes.sendJS(result, baseURL + filename);
return true;
if(baseURL.includes("includes/") || baseURL.includes("blogContent"))
{
includes.sendJS(result, baseURL + filename);
return true;
}
} }
//html //html
else if (filename.includes(".html")) else if (filename.includes(".html"))

+ 13
- 34
posts/category.js View File

@ -1,9 +1,8 @@
//DB query
/** DB query */
const sql = require('../utils/sql'); const sql = require('../utils/sql');
//file IO
const utils = require('../utils/utils.js');
/** Object used to render blog post previews */
const batchPreview = require('../posts/renderBatchOfPreviewes');
/** /**
* Renders all posts in a single category * Renders all posts in a single category
@ -11,7 +10,7 @@ const utils = require('../utils/utils.js');
* @param resultURL * @param resultURL
* @returns {*} * @returns {*}
*/ */
const renderPosts = function(resultURL)
const renderPosts = function(resultURL, page)
{ {
const splitURL = resultURL.split("/"); const splitURL = resultURL.split("/");
if(splitURL.length >= 3) if(splitURL.length >= 3)
@ -20,38 +19,16 @@ const renderPosts = function(resultURL)
{ {
sql.getPostsFromCategory(splitURL[2]).then(function(posts) sql.getPostsFromCategory(splitURL[2]).then(function(posts)
{ {
var promises = [];
posts.forEach(function(p)
{
promises.push(new Promise(function(res, rej)
{
require("../posts/singlePost.js")
.renderPreview(p).then(function(html)
{
res(html);
}).catch(function(error)
{
rej(error);
})
}));
});
Promise.all(promises).then(function(content)
{
resolve("<div class='col-md-8'>" + content.join('') + "</div>");
}).catch(function(error)
{
reject(error);
});
}).catch(function(err)
resolve(batchPreview.main(resultURL, posts, page, 5));
}).catch(function(error)
{ {
reject(err);
reject(error);
}) })
}); });
} }
else else
{ {
return utils.print404();
reject("Page Not Found");
} }
}; };
@ -60,14 +37,16 @@ module.exports=
/** /**
* Calls posts and sidebar modules to render blog contents in order * Calls posts and sidebar modules to render blog contents in order
* *
* @param res
* @param fileName request url
* @param requestURL
* @param request
* @returns {Promise}
*/ */
main: function(requestURL, request) main: function(requestURL, request)
{ {
return new Promise(function(resolve, reject) return new Promise(function(resolve, reject)
{ {
Promise.all([renderPosts(requestURL),
var page = request.query.page;
Promise.all([renderPosts(requestURL, page),
require("../sidebar/sidebar.js").main()]).then(function(content) require("../sidebar/sidebar.js").main()]).then(function(content)
{ {
resolve(content.join('')); resolve(content.join(''));

+ 5
- 27
posts/homePage.js View File

@ -1,42 +1,19 @@
const sql = require('../utils/sql'); const sql = require('../utils/sql');
const postRenderer = require('../posts/singlePost.js');
const batchPreview = require('../posts/renderBatchOfPreviewes');
/**Renders each recent post for the homepage of the website /**Renders each recent post for the homepage of the website
* *
* @param result * @param result
* @returns {*|Promise} * @returns {*|Promise}
*/ */
var renderRecentPosts = function()
var renderRecentPosts = function(baseURL, page)
{ {
return new Promise(function(resolve, reject) return new Promise(function(resolve, reject)
{ {
sql.getRecentPostSQL().then(function(posts) sql.getRecentPostSQL().then(function(posts)
{ {
var postPromises = [];
var content = "<div class='col-md-8'>";
posts.forEach(function(post)
{
postPromises.push(new Promise(function(res, rej)
{
postRenderer.renderPreview(post).then(function(cont)
{
res(cont);
}).catch(function(error)
{
rej(error);
})
}));
});
Promise.all(postPromises).then(function(cont)
{
content = content + cont.join('') + "</div>";
resolve(content);
}).catch(function(error)
{
reject(error);
})
resolve(batchPreview.main(baseURL, posts, page, 5));
}).catch(function(error) }).catch(function(error)
{ {
reject(error); reject(error);
@ -54,9 +31,10 @@ module.exports=
*/ */
main: function(requestURL, request) main: function(requestURL, request)
{ {
var page = request.query.page;
return new Promise(function(resolve, reject) return new Promise(function(resolve, reject)
{ {
Promise.all([renderRecentPosts(), require("../sidebar/sidebar.js").main()]).then(function(content)
Promise.all([renderRecentPosts(requestURL, page), require("../sidebar/sidebar.js").main()]).then(function(content)
{ {
resolve(content.join('')); resolve(content.join(''));
}).catch(function(error) }).catch(function(error)

+ 5
- 11
posts/posts.js View File

@ -1,7 +1,4 @@
//file io
const utils = require('../utils/utils.js');
//DB queries
/** DB queries */
const sql = require('../utils/sql'); const sql = require('../utils/sql');
@ -9,7 +6,6 @@ const sql = require('../utils/sql');
* Function responsible for calling the appropriate sql requests to query * Function responsible for calling the appropriate sql requests to query
* database and serve correct blog post * database and serve correct blog post
* *
* @param res the result sent to the client
* @param requestURL url requested from client * @param requestURL url requested from client
* @return {*|Promise} returns a resolved promise to preserve execution order * @return {*|Promise} returns a resolved promise to preserve execution order
*/ */
@ -30,7 +26,7 @@ const renderPost = function(requestURL)
} }
else else
{ {
return utils.print404();
reject("Page Not Found");
} }
}).then(function(html) }).then(function(html)
{ {
@ -42,10 +38,7 @@ const renderPost = function(requestURL)
} }
else else
{ {
utils.print404().then(function(html)
{
resolve("<div class='col-md-8'>" + html + "</div>");
});
reject("Page Not Found");
} }
}); });
}; };
@ -62,7 +55,8 @@ module.exports=
{ {
return new Promise(function(resolve, reject) return new Promise(function(resolve, reject)
{ {
Promise.all([renderPost(requestURL), require("../sidebar/sidebar.js").main()]).then(function(content)
Promise.all([renderPost(requestURL),
require("../sidebar/sidebar.js").main()]).then(function(content)
{ {
resolve(content.join('')); resolve(content.join(''));
}).catch(function(error) }).catch(function(error)

+ 55
- 0
posts/renderBatchOfPreviewes.js View File

@ -0,0 +1,55 @@
module.exports=
{
/**
* Renders a bunch of blog post previews to the user
*
* @param baseURL-- url of the page
* @param posts -- sql data about the posts to render
* @param currentPage -- the current page to render
* @param numOfPosts -- number of posts to render
* @returns {Promise} renders the html of the posts
*/
main: function(baseURL, posts, currentPage, numOfPosts)
{
if(typeof currentPage == "undefined")
{
currentPage = 1;
}
else
{
currentPage = Number(currentPage);
}
return new Promise(function(resolve, reject)
{
const promises = [];
for(var i = (currentPage-1) * numOfPosts; i < (currentPage-1) * numOfPosts + numOfPosts; i++)
{
if(i < posts.length)
{
promises.push(new Promise(function(res, rej)
{
require("../posts/singlePost.js")
.renderPreview(posts[i]).then(function(html)
{
res(html);
}).catch(function(error)
{
reject(error)
})
}));
}
}
promises.push(require('../posts/renderNextBar').main(baseURL, currentPage, numOfPosts, posts.length));
Promise.all(promises).then(function(content)
{
resolve("<div class='col-md-8'>" + content.join('') + "</div>");
}).catch(function(error)
{
reject(error);
});
});
}
};

+ 66
- 0
posts/renderNextBar.js View File

@ -0,0 +1,66 @@
/**
* Determines if the requested page is out of bounds
*
* @param page current page
* @param postsPerPage - number of posts rendered on each page
* @param totalPosts - total posts in this category/total
* @returns {boolean} if this is a valid page
*/
const isValidPage = function(page, postsPerPage, totalPosts)
{
return !(page === 0 || page -1 >= totalPosts/postsPerPage);
};
module.exports=
{
/**
* Renders two buttons on the bottom of the page to
* go to the left or right
*
* Used by the home page and categories pages
* @param baseURL -- base url of page being rendered
* @param currentPage -- current page being rendered
* @param postsPerPage -- number of posts on each page
* @param totalPosts -- total amount of posts in the category
* @returns {Promise} promise which renders the buttons
*/
main: function(baseURL, currentPage, postsPerPage, totalPosts)
{
return new Promise(function(resolve, reject)
{
if(!isValidPage(currentPage, postsPerPage, totalPosts))
{
reject("Invalid Page");
}
var nextPage = currentPage + 1;
var previousPage = currentPage - 1;
var olderPosts = "";
var newerPosts = "";
if (isValidPage(previousPage, postsPerPage, totalPosts))
{
newerPosts = "<button class=\"btn btn-secondary btn-lg " +
"w3-padding-large w3-white w3-border\" onclick=\"location.href='" +
baseURL + "?page=" + previousPage +
"'\"><b>Newer Posts &raquo;</b></button>";
}
if (isValidPage(nextPage, postsPerPage, totalPosts))
{
olderPosts = "<button class=\"btn btn-secondary btn-lg " +
"w3-padding-large w3-white w3-border\" onclick=\"location.href='" +
baseURL + "?page=" + nextPage +
"'\"><b>Older Posts &raquo;</b></button>";
}
resolve(" <div class=\"row\">\n" +
" <div class=\"col-6\">" + newerPosts + "</div>\n" +
" <div class=\"col-6\"><span class=\"float-right\">" + olderPosts + "</span></div>\n" +
" <br><br></div>");
})
}
};

+ 20
- 6
sites/blog.js View File

@ -8,6 +8,9 @@ const contentLoader = require('../includes/staticContentServer.js');
//caching program to make the application run faster //caching program to make the application run faster
const cache = require('memory-cache'); const cache = require('memory-cache');
//file io
const utils = require('../utils/utils.js');
/** /**
* @author Jeffery Russell 11-3-18 * @author Jeffery Russell 11-3-18
* *
@ -38,7 +41,12 @@ module.exports=
} }
else else
{ {
const html = cache.get(filename);
var page = request.query.page;
if(typeof page == "undefined")
page = 1;
page = Number(page);
const html = cache.get(filename + "?page=" + page);
result.writeHead(200, {'Content-Type': 'text/html'}); result.writeHead(200, {'Content-Type': 'text/html'});
if (html == null) { if (html == null) {
@ -54,9 +62,12 @@ module.exports=
if (urlSplit.length >= 2 && urlSplit[1] === 'category') //single category page if (urlSplit.length >= 2 && urlSplit[1] === 'category') //single category page
file = "../posts/category.js"; file = "../posts/category.js";
else else
{
file = "../posts/posts.js"; file = "../posts/posts.js";
page = 1; // all posts are single page, everyone must be one to ensure
// cache is not tricked into storing same blog post a ton of times
}
} }
Promise.all([includes.printHeader(), Promise.all([includes.printHeader(),
@ -65,12 +76,15 @@ module.exports=
{ {
result.write(content.join('')); result.write(content.join(''));
result.end(); result.end();
cache.put(filename, content.join(''));
cache.put(filename + "?page=" + page, content.join(''));
}).catch(function (err) }).catch(function (err)
{ {
console.log(err);
throw err;
cache.del(filename + "?page=" + page);
utils.print404().then(function(content)
{
result.write(content);
result.end();
})
}); });
} }
else else

+ 0
- 3
sites/projects.js View File

@ -1,6 +1,3 @@
//file io
const utils = require('../utils/utils.js');
//used to parse the request URL //used to parse the request URL
const url = require('url'); const url = require('url');

+ 1
- 1
utils/sql.js View File

@ -196,7 +196,7 @@ module.exports=
*/ */
getRecentPostSQL: function() getRecentPostSQL: function()
{ {
return fetch("select * from posts order by post_id desc limit 10");
return fetch("select * from posts order by post_id desc");
}, },

Loading…
Cancel
Save