From f0a654ca3e9dbac4113483e9d9b238cf19188759 Mon Sep 17 00:00:00 2001 From: lauraF Date: Mon, 16 May 2022 16:16:28 +0200 Subject: [PATCH] =?UTF-8?q?blogController=20einf=C3=BCgen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controllers/blogController.js | 52 +++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 controllers/blogController.js diff --git a/controllers/blogController.js b/controllers/blogController.js new file mode 100644 index 0000000..784a76d --- /dev/null +++ b/controllers/blogController.js @@ -0,0 +1,52 @@ +var fs = require('fs'); +//erstellt JSONObjekt +let rawdata = fs.readFileSync('./public/models/blog.json'); +//wandelt JSONObjekt in JsObjekt +let blogInhalt = JSON.parse(rawdata); + +var getAllPosts=(req, res) => { + for (i = 0; i < blogInhalt.length; i++){ + console.log(blogInhalt[i].id, "." , blogInhalt[i].title); + } + res.send({ blogInhalt }); +} + +var createPost = (req, res) => { + let blogeintrag = { + id : blogInhalt.length + 1, + title : req.body.title, + username : req.body.username, + date : req.body.date, + text : req.body.text + } + + console.log(blogeintrag); + + //hänge blogeintrag an blogInhalt + blogInhalt.push(blogeintrag); + + let date = JSON.stringify(blogInhalt, null, 2); + + fs.writeFileSync('./public/models/blog.json', date); + + res.render('blogPost', { title: 'Nächster Post' }) +} + +var getPost = (req, res) => { + let blogID = req.params.postID; + + if(blogID > blogInhalt.length){ + console.log("kein entsprechender Eintrag vorhanden"); + res.send("kein entsprechender Eintrag vorhanden") + } else { + console.log(blogInhalt[blogID - 1]); + res.send(blogInhalt[blogID - 1]); + } + +} + +module.exports = { + getAllPosts, + createPost, + getPost +} \ No newline at end of file