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:
Technical Information
buildResponse is a function that returns a JSON response constructed from the two parameters it accepts.
Parameter Order | Parameter Type | Description |
---|---|---|
First | Error Object | An object that represents an error and is represented by a code and a message. |
Second | Data Response | The 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 Name | PropertyType | Usage |
---|---|---|
code | Integer/String | Specifies the code of the Error. |
msg | String | States the message of the Error. |
... # somewhere in the code res.json(req.soajs.buildResponse(null, { 'a': 'b' })); ...
{"result":success,"data":{ 'a': 'b' }}