How is the best way to write an app.request (get/post) reusable?


#1

Hi, How is the best way to write an app.request (get/post) reusable?
In my app I have a lot of request (get/post) and for each task I write something like this…

 //GET
 var url = endpoint + 'users/';
 var query = '{"id": "20"}';
app.request.get(url,
              {keys: key,
               where: query,
               username: username,
               lastname: lastname,
               data: data
              },
              function (data) {

                data = JSON.parse(data);
                ….code....

              }

            //POST

            var url = endpoint + 'users/';
            app.request.post(url,
              {keys: key,
               username: username,
               lastname: lastname,
               data: data
              },
              function (data) {

                data = JSON.parse(data);
                switch(d.response.code)
	  		{
	  			case '400': ...code.. break;

	  			case '200': ...code… break;
	  					
	  		
	  	       }

              }

The two things that changing in my request is the type (get or post) and the params(sometimes I have all the params above and sometimes only two)… I’d like to create only one function, but I don’t know how to do it. Sorry for my question, I’m a beginner. Thank you in advance for your help.


#2

not recommended

app.request.setup({
  url:'https://endpoint/users',
  data:{key:'key',lastname:'lastname'},
  success:function(data){
    console.log(data)
  }
})

app.request({method:'GET'});
app.request({method:'POST'});

docs:

app.request.setup(parameters)- Set default values for future Ajax requests. 
Its use is not recommended

parameters - object - Default requests parameters

#3

Thank you plpl… in this way I can change dinamically only the method and the params not… right? however is not recommended


#4

Or something like:

function requestUsers(params) {
  return new Promise((resolve, reject) => {
    app.request(app.utils.extend(
      // defaults
      {
        url: endpoint + 'users/',
        data: {
          keys: key,
          username: username,
          lastname: lastname,
        },
        success(data) {
          resolve(data);
        },
        error() {
          reject();
        },
      },
      // extend with
      (params || {})
    )
  });
}

requestUsers({
  method: 'GET',
  data: {
    where: query,
    data: data,
  }
}).then(function (data) {
  data = JSON.parse(data);
  // ...
});

requestUsers({
  method: 'POST',
  data: {
    data: data,
  }
}).then(function (data) {
  data = JSON.parse(data);
  // ...
})



#5

Thank you Vladimir… but on the console I have this error

  TypeError: applicationCache.request is not a function

#6

It was a typo, should be app.request


#7

Thank you Vladimir, is it also possible change dinamically the last path of the url?