Cover photo by Christopher Robin Ebbinghaus on Unsplash
You can install web-hmm via the node package manager.
npm install web-hmm
You want to import it
const app = require('web-hmm').createApp();
Create some handlers, i'm using C.R.U.D.
POST new blog post
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(); }); });
GET every post (limit = 5)
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(); });
GET a specified post
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(); });
PATCH a specified post
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(); }); })
You can also serve static files or make "middleware"
app.middleware.use( app.middleware.predefined.static( './public/react', // filesystem path '/react' // http route ), 'STATIC_SERVE' // optional name for middleware debugging );
// 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');
Create the server and start listening for requests
app.createServer(); let port = process.env.PORT || 3000 app.listen(port, () => console.log(`App listening on port ${port}`));
Final output: Github Gist
And now you should be able to hack this to anything you want!
Change in your own database, serve a front-end, etc.
Top comments (2)
This is very good!
Thanks :)