Response

Objective


When you build your service, SOAJS adds its buildResponse tool to the request object. This tool standardizes the response that should be returned by your service API. All responses are encapsulated in a valid REST API JSON schema supporting both successful and error responses.


This space will show you:

  1. Technical information about buildResponse
  2. Code examples



Technical Information


buildResponse is a function that returns a JSON response constructed from the two parameters it accepts.

Parameter OrderParameter TypeDescription
FirstError ObjectAn object that represents an error and is represented by a code and a message.
SecondData ResponseThe data that the API should return.

The response returned contains either a successful result or a failure one. In the case of a successful response, the data is provided whereas if the response is a failure, a JSON object is returned stating the error message and its code.

The below snippet shows both possible responses returned by an API:

# failure response
{
    "result":false,
    "errors":{
        "codes":["400"],
        "details":[
            {"code":"400","message":"this is an error"}
        ]
    }

}

# successful response
{
    "result": true,
    "data": "API data response..."
}

# if we put the m together the schema will look like 
{
    "result": true || false,
    "data": "API data response...",
	"errors":{
        "codes":["400"],
        "details":[
            {"code":"400","message":"this is an error"}
        ]
    }
}

Code Examples


Case of an Error:

In the event of an error, buildResponse only uses the first parameter to construct a failure JSON response and return it. The first parameter is an object that holds 2 properties which define the Error that should be returned.

Property NamePropertyTypeUsage
codeInteger/StringSpecifies the code of the Error.
msgStringStates the message of the Error.
Code
...
    # somewhere in the code
    res.json(req.soajs.buildResponse(null, { 'a': 'b' }));
...
Response
{"result":success,"data":{ 'a': 'b' }}