DEV Community

Discussion on: Best practices querying APIs via cloud functions

Collapse
kaoskater08 profile image
Eddie Hale • Edited on

Architecturally I don't believe there is a best practice with Cloud Functions specifically. Your idea of injecting the endpoint makes it flexible for any future APIs you have, and would follow the SOLID design principles.

You could send an object with all necessary data and only have one function, using a library like request. Then all you have to do is structure your input parameters to match.

Something like this:

var options = {
  baseUrl: 'https://localhost:3001',
  uri: '/api/user',
  method: 'GET',
  headers: {
    date: new Date().toUTCString(),
  }
}

makeApiRequest(options)

var options = {
  baseUrl: 'https://localhost:3001',
  uri: '/api/user',
  method: 'POST',
  headers: {
    date: new Date().toUTCString(),
  }
  body: {
    firstName: 'Eddie'
    lastName: 'Hale'
  }
}

makeApiRequest(options)

function makeApiRequest(options) {
  request(options, (err, response) => {
    if(err) console.log(err);
    else {
      console.log(response);
    }
  }
}