Thomas Wade 3311a17b01 Rework post functionality
Conforms to the new post format and validates incoming posts
2018-10-20 20:03:03 +10:30

70 lines
1.8 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("./")); // Serve static files from root
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": "./"});
// });
// Root route, respond with with index.html
app.get("/", function(req, res) {
res.sendFile("./index.html");
});
// Posts route, return posts.json
app.get("/posts", function(req, res) {
res.json(JSON.parse(fs.readFileSync('./data/posts.json')));
});
// Posts route, digest received post
app.post("/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);
});
// Start listening
app.listen(8080, function (){
console.log("Listening on port 8080");
});
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;
}
}