Create a Service to Handle HTTP Requests (Pre-Vinson)
The following example shows the required components of a service in pre-Vinson implementations of SuiteCommerce Advanced (SCA).
function service (request)
{
'use strict';
var Application = require('Application');
try
{
var method = request.getMethod();
var QuestionsAndAnswersModel = require('QuestionsAndAnswers.Model');
switch (method)
{
case 'GET':
var page = request.getParameter('page');
, result = QuestionsAndAnswersModel.search(page);
Application.sendContent(result,{'cache': response.CACHE_DURATION_LONG});
break;
case 'POST':
var data = JSON.parse(request.getBody() || '{}')
, result = QuestionsAndAnswersModel.create(data)
Application.sendContent(result, {'status': 201});
break;
default:
Application.sendError(methodNotAllowedError);
}
}
catch (e)
{
Application.sendError(e);
}
}
To create a custom service for a pre-Vinson implementation of SCA, you must perform the following:
Step 1: Create a Reference to the Application Module
The following code enables the service to access methods defined in the Application module.
var Application = require('Application');
The Application module contains HTTP methods that the service uses to send data to the frontend application and return any errors. This module is defined in the ssp_libraries.js file. See The ssp_libraries.js File.
Services in SCA do not include the HTTP response as a parameter. Services return a JSON object using the sendContent
method defined in the Application module.
Step 2: Define a try/catch Block
The body of a service must be included within a try/catch block. This ensures that any errors that occur are handled correctly. These errors are passed back to the frontend application and are handled by the ErrorManagement module.
Step 3: Create a Reference to the Backend Model
var QuestionsAndAnswersModel = require('QuestionsAndAnswers.Model');
This statement enables the service to call methods defined in the backend model.
Step 4: Define a Switch Statement to Handle the HTTP Request
The main task of a service is to specify how to handle the HTTP action specified by the request. This is generally performed by a switch
statement which contains a case
statement for each HTTP method supported by the service.
switch (method)
{
case 'GET':
var page = request.getParameter('page');
, result = QuestionsAndAnswersModel.search(page);
Application.sendContent(result,{'cache': response.CACHE_DURATION_LONG});
break;
case 'POST':
var data = JSON.parse(request.getBody() || '{}')
, result = ProductReview.create(data)
Application.sendContent(result, {'status': 201});
break;
default:
Application.sendError(methodNotAllowedError);
The switch
statement also contains a default
statement to handle errors related to the HTTP request. This statement returns an error which is sent back to the frontend application and handled by the ErrorManagement module.