Abstracting those Boring API Requests & Endpoints
Tags: javascript, webdev, tutorial
Published: 2020-12-17 02:42:23


As a developer, there is nothing more annoying than creating HTTP request functions to consume or send data every time the back-end has new API endpoints. This typically happens, you are forced to create the API endpoints and the equivalent client code. As it grows, it will make integrations more complex. Our mission was to solve the complexity problem.

## The Problem
Let's experience how tedious creating API endpoints are.

```javascript
// Server.js
const  express = require('express')
const  app = express()
const  bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended:  true }))
const  cors = require('cors')
app.use(cors())
app.listen(3000)

class Person {
	constructor() {
		this.name = 'Trinmar Pogi'
	}
	run (speed) {
		return  `${this.name} is running at ${speed}km/h`
	}
	eat (food) {
		return  `${this.name} is eating ${food}`
	}
}

let human = new Person('Trinmar Pogi') 

app.get('/run', function (req, res) {
	res.json(human.run(req.query.speed))
})

app.get('/eat', function (req, res) {
	res.json(human.run(req.query.food))
})
```
As you can see here , it is a simple express server app. It has a `human object` which is an instance of `class Person`. If you want to expose a function for the client to use, you need to create an API endpoint for it.

For example we will create a `talk function` revising the `class Person`
```javascript
// Server.js
class Person {
	constructor() {
		this.name = 'Trinmar Pogi'
	}
	run (speed) {
		return  `${this.name} is running at ${speed}km/h`
	}
	eat (food) {
		return  `${this.name} is eating ${food}`
	}
	talk (speech) {
		return  speech
	}
}
```
you will be needing this kind of endpoint again.
```javascript
// Server.js
app.get('/talk', function (req, res) {
	res.json(human.run(req.query.speech))
})
```
imagine you will have hundreds of functions needed to be exposed. 🤣 

> aray koh beh! awit yaw ko na

## The solution
This inspires me to create an abstraction of this problem. I am a lazy person like Juan Tamad. I hate repetitive tasks or work.

Just install **[shared-node](https://www.npmjs.com/package/shared-node)**, a library that enables developers to **directly call a  function or method of a remote object** and can be shared to any frontend frameworks


```bash
npm install shared-node
```
or
```bash
yarn add shared-node
```
add this magical code exporting the objects you want to be exposed to your client.
```javascript
// Server.js
const { sharedCodeServer } = require('shared-node')
app.use(sharedCodeServer({ human }))
```

***the whole code of the server are shown below***
```javascript
// Server.js
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
const cors = require('cors')
app.use(cors())
app.listen(3000)

class Person {
  constructor() {
    this.name = 'Trinmar Pogi'
  }
  run(speed) {
    return `${this.name} is running at ${speed}km/h`
  }
  eat(food) {
    return `${this.name} is eating ${food}`
  }
  talk(speech) {
    return speech
  }
}

let human = new Person('Trinmar Pogi')

// see the magic here 🧙
const { sharedCodeServer } = require('shared-node')
app.use(sharedCodeServer({ human }))
```
If you are using bundlers like webpack, rollup, or parcel, you can use the same npm package. But in this case, will just use the plain vanilla HTML app and the `sharedCodeClient function`  shown below.
```html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://unpkg.com/shared-node/dist/index.js"></script>
</head>

<body>
  <button onclick="run(100)">slow</button>
  <button onclick="eat('big banana')">medium</button>
  <button onclick="talk('ang pogi ko')">fast</button>
  <script>
    const { sharedCodeClient } = sharedNode;
    let person = null;
    (async () => {
      const { human } = await sharedCodeClient('http://localhost:3000')
      person = human
      console.log(await human.run(999))
    })()

    const run = async speed => alert(await person.run(speed))
    const eat = async food => alert(await person.eat(food))
    const talk = async speech => alert(await person.talk(speech))
  </script>
</body>

</html>
```
**Ta-da! Voila! Ciao! Bingo! just run your server and html app!** 

## Conclusion
Being lazy is awesome! It drives innovation 🤣😁😎 Abstracting API centric development was successful. The front-end and back-end can now share components and interact seamlessly.

## UPDATE!!!
you can use **[real-share](https://github.com/trinly01/real-share)**, my new library with same concept but different implementation using websockets

<br/>
<br/>
<br/>
<br/>
<br/>
***you can also subscribe to my personal youtube channel***

[![](http://img.youtube.com/vi/vg5RLL24vkY/0.jpg)](http://www.youtube.com/watch?v=vg5RLL24vkY "")


# *Join and support our Community* <br /> **Web and Mobile Developers PH** <br/> [ [Facebook Page](https://fb.com/webmobile.ph) | [Group](https://fb.com/groups/webmobile.ph/) ]