DEV Community

Trinmar Boado
Trinmar Boado

Posted on • Updated on

Abstracting those Boring API Requests & Endpoints

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.

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

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

// 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
    }
}
Enter fullscreen mode Exit fullscreen mode

you will be needing this kind of endpoint again.

// Server.js
app.get('/talk', function (req, res) {
    res.json(human.run(req.query.speech))
})
Enter fullscreen mode Exit fullscreen mode

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, a library that enables developers to directly call a function or method of a remote object and can be shared to any frontend frameworks

npm install shared-node
Enter fullscreen mode Exit fullscreen mode

or

yarn add shared-node
Enter fullscreen mode Exit fullscreen mode

add this magical code exporting the objects you want to be exposed to your client.

// Server.js
const { sharedCodeServer } = require('shared-node')
app.use(sharedCodeServer({ human }))
Enter fullscreen mode Exit fullscreen mode

the whole code of the server are shown below

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

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.

<!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>
Enter fullscreen mode Exit fullscreen mode

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, my new library with same concept but different implementation using websockets











you can also subscribe to my personal youtube channel

Join and support our Community
Web and Mobile Developers PH
[ Facebook Page | Group ]

Top comments (0)