How to use web-hmm to create APIs
Tags: webhmm, api, node, javascript
Published: 2020-10-23 14:05:57

<span>Cover photo by <a href="https://unsplash.com/@cebbbinghaus?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Christopher Robin Ebbinghaus</a> on <a href="https://unsplash.com/s/photos/javascript?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>

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

You want to import it
```js
const app = require('web-hmm').createApp();
```

Create some handlers, i'm using C.R.U.D.

POST new blog post
```js
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)
```js
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
```js
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
```js
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"
```js
app.middleware.use(
  app.middleware.predefined.static(
    './public/react', // filesystem path 
    '/react' //          http route 
  ), 'STATIC_SERVE' //   optional name for middleware debugging
);
```
```js
// 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
```js
app.createServer();

let port = process.env.PORT || 3000
app.listen(port, () => console.log(`App listening on port ${port}`));
```

Final output: [Github Gist](https://gist.github.com/LukasDoesDev/37accc97b632c8f578da50f2788c9135)


And now you should be able to hack this to anything you want!
Change in your own database, serve a front-end, etc.