DEV Community

Cover image for How to use web-hmm to create APIs
Lukas Does Dev
Lukas Does Dev

Posted on

How to use web-hmm to create APIs

Cover photo by Christopher Robin Ebbinghaus on Unsplash

You can install web-hmm via the node package manager.

npm install web-hmm
Enter fullscreen mode Exit fullscreen mode

You want to import it

const app = require('web-hmm').createApp();
Enter fullscreen mode Exit fullscreen mode

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();
  });
});
Enter fullscreen mode Exit fullscreen mode

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();
});
Enter fullscreen mode Exit fullscreen mode

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();
});
Enter fullscreen mode Exit fullscreen mode

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();
  });
})
Enter fullscreen mode Exit fullscreen mode

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
);
Enter fullscreen mode Exit fullscreen mode
// 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');
Enter fullscreen mode Exit fullscreen mode

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}`));
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
zdev1official profile image
ZDev1Official

This is very good!

Collapse
 
lukasdoesdev profile image
Lukas Does Dev

Thanks :)