[NJS] Creating a new post
3 min read
Last post in the series is about creating a new post. This wasn't really needed, since the whole point of having my blog in Dropbox was to use any markdown editor I desire, save the file, run the sync command, and have it live, but for the sake of learning, I went ahead and added this feature too.
First, the routes:
router.get("/create/" + process.env.MY_SYNC_KEY, function(req, res) {
res.render("create-post", {
title: "Create",
metadata: "Create a post"
})
})
router.post("/create", function(req, res) {
if (req.params.token != process.env.MY_SYNC_KEY) { res.redirect("/"); return }
const body = req.body
// Create the file first, if it doesn't work, stay on the page.
Dropbox.createFile(body).then(function(data) {
if (!data) { res.end(); return }
res.redirect("/cmd.sync/" + process.env.MY_SYNC_KEY)
})
})Then the createFile function:
const request = require("request")
Dropbox.createFile = function(body) {
return new Promise(function(resolve) {
const fileContents = body.title + "\n\n" + body.body
const fileName = "posts/" + body.datetime + "-" + body.title + ".md"
const options = {
method: "PUT",
url: "https://api-content.dropbox.com/1/files_put/auto/" + fileName + "?overwrite",
headers: {
"Content-Type": "text/plain",
Authorization: "Bearer " + process.env.DB_ACCESS_TOKEN
},
body: fileContents
}
request(options, function(err) {
if (err) {
console.log("Creating " + fileName + " failed.")
}
else {
resolve(true)
}
})
})
}And lastly, the view is just a <form method="post" action="/create"> with some text inputs and an <input class="button" type="submit">.
I hope I managed to explain things properly throughout the series, I hope I haven't forgotten anything, and if there's anything to fix or improve, don't hesitate to contact me; I'd be more than glad to discuss about anything.