Thomas Wade a205dc9c7e Add FAQ functionality and some style tweaks
Switched to HTML5-style routing
Reworked Express backend to accommodate HTML5-style routing
Links are now highlighted with a black background and white foreground
Reworked spacing on H1s
Added classes to nav buttons
2018-10-30 17:33:24 +10:30

88 lines
2.3 KiB
JavaScript

var fs = require('fs'); // Filesystem
var express = require('express'); // Express
var bodyParser = require('body-parser'); // Data conversion, JSON parsing
// Set up Express
var app = express();
app.use(express.static("./static/")); // Serve static files from /static/
app.use(express.json()); // Parse JSON in requests
// app.use("/", (req, res, next) => // Finally send a 404 page
// {
// res.status(404).sendFile("404.html", {"root": "./"});
// });
// Posts route, return posts.json
app.get("/api/posts", function(req, res)
{
res.json(JSON.parse(fs.readFileSync('./data/posts.json')));
});
// Posts route, digest received post
app.post("/api/posts", function(req, res)
{
var postsFile = fs.readFileSync('./data/posts.json');
var posts = JSON.parse(postsFile);
var incomingData = req.body;
if (validatePost(incomingData))
{
posts.unshift(incomingData);
}
else
{
res.status(400).json({"error":"Failed to validate post"});
return;
}
fs.writeFile('./data/posts.json', JSON.stringify(posts), (e) =>
{
if (e)
{
res.sendStatus(500);
throw e;
}
});
res.sendStatus(204);
});
// About route, return about.json
app.get("/api/about", (req, res) =>
{
res.json(JSON.parse(fs.readFileSync('./data/about.json')));
});
// FAQ route, return faq.json
app.get("/api/faq", (req, res) =>
{
res.json(JSON.parse(fs.readFileSync('./data/faq.json')));
});
// Default route, serve static index.html and let AngularJS handle the remainder
app.get("/*", (req, res) =>
{
res.sendFile("./static/index.html", {root: __dirname})
});
// Start listening
app.listen(8080, function()
{
console.log("Listening on port 8080");
});
// Validates a post object conforms to the standard we're expecting
function validatePost(post)
{
try
{
// Check types of each expected property and assume they're there
return (typeof post.title === "string" && typeof post.author === "string" && typeof post.date === "number" && Array.isArray(post.tags) && typeof post.content === "string");
}
catch (e)
{
// Object clearly isn't what we're expecting
return false;
}
}