Created
October 23, 2020 13:57
-
-
Save LukasDoesDev/37accc97b632c8f578da50f2788c9135 to your computer and use it in GitHub Desktop.
Revisions
-
LukasDoesDev created this gist
Oct 23, 2020 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,94 @@ const app = require('web-hmm').createApp(); // Add this middleware before routing methods or the static file serve method app.middleware.use((req, res) => { // todo console.log(` || Request Type: ${req.method}`); console.log(` || Request URL: ${req.url}`); console.log(` || Date & Time: ${new Date(Date.now()).toString()}`); next(); // Pass on for next middleware to use }, 'LOGGING_MIDDLEWARE'); app.methods.POST('/api/posts', (req, res) => { var data = ''; req.on('data', chunk => { data += chunk; }); req.on('end', () => { let post = JSON.parse(data); post.date = Date(Date.now).toString(); // Database stuff res.sendJSON(JSON.stringify(post)); res.end(); }); }); app.methods.GET('/api/posts', (req, res) => { // Database stuff let posts = []; let makePost = (n) => ({ author: `LukasDoesDev`, title: `web-hmm is CRAZY ${n}`, content: `This is example content #${n}!`, }); [1, 2, 3, 4, 5].forEach((n, i) => posts.push(makePost(n))); res.sendJSON(JSON.stringify(posts)); res.end(); }); app.methods.GET('/api/post/:id', (req, res) => { let id = req.params.id.value; // Database stuff var post = { author: `LukasDoesDev`, title: `web-hmm is CRAZY ${id}`, content: `This is example content #${id}!`, }; res.sendJSON(JSON.stringify(post)); res.end(); }); app.methods.PATCH('/api/post/:id', (req, res) => { let id = req.params.id.value; var data = ''; req.on('data', chunk => { data += chunk; }); req.on('end', () => { let post = JSON.parse(data); // Database stuff var postExample = { author: 'LukasDoesDev', title: 'web-hmm is CRAZY', content: 'This is example content!' }; var updatedPost = {...postExample, ...post} updatedP ost.date = Date(Date.now).toString(); res.sendJSON(JSON.stringify(updatedPost)); res.end(); }); }) app.middleware.use( app.middleware.predefined.static( './public/react', // filesystem path '/react' // http route ), 'STATIC_SERVE' // optional name for middleware debugging ); app.createServer(); let port = process.env.PORT || 3000; app.listen(port, () => console.log(`App listening on port ${port}`));