Services

Services allow the creation of http endpoints without binding them to specific paths. Each service must have a JavaScript controller file and optionally an XML descriptor placed in the folder services/[service-name]

Descriptor

The service descriptor is an XML file that is used to define which rights are required to access the service.

The descriptor file must have the same name as the service, i.e. services/[service-name]/[service-name].xml:

<service>
  <allow>
    <principal>role:system.admin</principal>
    <principal>role:myapp.myrole</principal>
  </allow>
</service>

Controller

A service controller handles requests to the service. The controller is a required file written in JavaScript and must have the same name as the service, i.e. services/[service-name]/[service-name].js.

A controller exports a function for each type of HTTP request that should be handled. The handle function takes the request object as a parameter and returns the response object (see HTTP Controllers).

The following example is a simple service that returns a JSON object with the date and a counter.

var counter = 0;

exports.get = function(req) {

  counter++;

  return {
    body: {
      time: new Date(),
      counter: counter
    },
    contentType: 'application/json'
  };

};

Access

The service can then be accessed on a relatively mounted URL, as seen below, where application is the application name (without version):

*/_/service/[application]/[service-name]

The portal function serviceUrl() will create a dynamic URL for a service.

serviceUrl({service [,application] [,type] [,params]})
Arguments:
  • service (string) – Name of the service.
  • application (string) – Application where the service exists. Default is current application.
  • type (string) – URL type. Either server (server-relative URL) or absolute. Default is server.
  • params (object) – Custom parameters to append to the url.
Returns:

The relative or absolute URL to the service.

API

The detailed API documentation may be found here.