DEV Community 👩‍💻👨‍💻

Igor Alexandrov for JetRockets

Posted on • Originally published at jetrockets.pro

Request Api Adapter

When developing client applications, it is often necessary to send requests to the server.

// ...
client({ url: "/users.json", method: "GET" }).then(...)

We can make our lives a little easier. A convenient abstraction is apiAdapter

// apiAdapter.js
function getUsers() {
  return { url: "/users.json", method: "GET" };
}

const apiAdapter = createAdapter(client, {}, {
  getUsers,  
})

By defining a request in one place, you can now simply call the adapter method you want.

import apiAdapter from './apiAdapter'

apiAdapter.getUsers().then(...)

It is also a useful option to specify basic settings for all requests, as well as handling errors and successful requests.

const apiAdapter = createAdapter(
  client,
  { withCredentials: true },
  {
    getUsers,  
  },
  successHandler,
  errorHandler, 
)

Github
Live example

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!