DEV Community

Discussion on: Which functions/methods do you...

Collapse
 
ajinspiro profile image
Arun Kumar

let callApi=(path) => fetch(path).then(response => response.json())

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

This will work just for GET requests without authentication, let me do a little tweak on it by just adding an optional "options" parameter 😁

services/api/utils.js

const requestBuilder = (path, options) => fetch(path, options).then(response => response.json()).catch(error => error)
Enter fullscreen mode Exit fullscreen mode

now you can perform any HTTP verb request on a new layer of functions like

PUT example (POST will look mostly the same):
services/api/users.js:

const updateUser = (user) => requestBuilder( Process.env.API_URL, {  
  method: 'PUT',
  body: JSON.stringify(user),
  headers: {
    'Content-Type': 'application/json',
    Authorization: getToken(),
  },
}).then( result => result);
Enter fullscreen mode Exit fullscreen mode

Working example

You can try it in your browser terminal right now:

services/api/pokemon.js:

const getPokemonByName = (pokemon) =>requestBuilder(`https://pokeapi.co/api/v2/pokemon/${pokemon}`, { method: 'GET' })
Enter fullscreen mode Exit fullscreen mode

usage:

getPokemonByName('ditto')
Enter fullscreen mode Exit fullscreen mode
Collapse
 
siddsarkar profile image
Siddhartha Sarkar

This is my favourite one and universal too:

/**
 * Global network request handler
 * @param {RequestInfo} url url to fetch
 * @param {RequestInit=} options fetch options
 * @returns json response
 */
const processFetchRequest = async (url, options) => {
  const ts = Date.now();
  const method = options?.method || 'GET';
  const endpoint = url.match(
    /((?!\S+\s)?\S*[/].*?(?:\S+\s)?\S*[/])([\s\S]*)/,
  )[2];

  const response = await fetch(url, options);
  console.log(`${method}${response.status}: ${Date.now() - ts}ms /${endpoint}`);

  if (response.ok) {
    return response.json();
  }
  throw response.json();
};

export default processFetchRequest;
Enter fullscreen mode Exit fullscreen mode