Search code examples
jqueryajaxamplifyjs

How to build request with optional data using AmplifyJS?


I have a RESTful web service with this format:

/users?age={age}

As it is defined, the web service works whether I add age parameter or not. So both examples are correct:

/users

or

/users?age=18

The amplify's request definition:

amplify.request.define( "usersService", "ajax", {
  url: "/users",
  type: "GET",
  data: {age : "{age}"}
});

Invocation that works:

var myAge = 18;
amplify.request("usersService", {age : myAge});

Result is:

GET /users?age=18 
Response code: 200 OK

Invocation that does not work:

var myAge = null;
amplify.request("usersService", {age : myAge});

Result is:

GET /users?age=
Response code: 400 BAD REQUEST

The correct result I was expecting when age is not defined is:

GET/users
Response code: 200 OK

Any idea how to make this example works?

Thanks in advance. Regards Neuquino


Solution

  • The solution was not to define the "data" in request.define and adding or not the age attribute to the invocation.

    var input = null;
    if(myAge != null){
      input.age = myAge
    }
    amplify.request("usersService",input);
    
    
    amplify.request.define( "usersService", "ajax", {
      url: "/users",
      type: "GET",    
    });
    

    input is merged in the body, so if is empty, nothing is sent.