Skip to content

Instantly share code, notes, and snippets.

@LukasDoesDev
Created Oct 23, 2020
Embed
What would you like to do?
web-hmm template code
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}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment