diff --git a/api/post.js b/api/post.js new file mode 100644 index 0000000..043f526 --- /dev/null +++ b/api/post.js @@ -0,0 +1,37 @@ +const logger = require(`${__base}/logger`) +const establishedDatabase = require(`${__base}/database`); + +const md = require("markdown-it")(); + +class PostRepository { + constructor(database) { + this.database = database || establishedDatabase; + } + + renderPost(id) { + return this.getPost(id) + .then(post => { + if (post) { + return Promise.resolve(md.render(post.markdown)) + } + + throw new Error("Post not found"); + }) + } + + getPost(id) { + const query = "SELECT * from posts where id = $1"; + return this.database.get(query, [id]) + } + + updatePost(id, markdown="## database testost") { + const query = `UPDATE posts SET markdown = $1 WHERE id = $2`; + + const post = this.database.update(query, [markdown, id]); + + return post + .then(post => true) + } +}; + +module.exports = PostRepository; diff --git a/api/webserver/controllers/postController.js b/api/webserver/controllers/postController.js new file mode 100644 index 0000000..5a42f97 --- /dev/null +++ b/api/webserver/controllers/postController.js @@ -0,0 +1,50 @@ +const logger = require(`${__base}/logger`); + +const PostRepository = require(`${__base}/post`); +const postRepository = new PostRepository(); + +function getPost(req, res) { + const { id } = req.params; + + return postRepository.getPost(id) + .then(post => res.json({ + success: true, + post: post + })) +} + +function renderPost(req, res) { + const { id } = req.params; + + return postRepository.renderPost(id) + .then(markdown => res.json({ + success: true, + markdown: markdown + })) +} + +function updatePost(req, res) { + const { id } = req.params; + const { markdown } = req.body; + + return postRepository.updatePost(id, markdown) + .then(fileUpdated => res.json({ + message: "Successfully updated post " + id, + filename: fileUpdated, + success: true + })) + .catch(error => { + const { httpStatus, message } = error; + + return res.status(httpStatus || 500).json({ + message: message, + success: false + }) + }) +} + +module.exports = { + getPost, + renderPost, + updatePost +};