index.js in RESTApps

index.js is the entry point and route configuration for a RESTApp. This is where the RESTApp's endpoints are created. The SiteVision Public API is accessible.

The URL to a RESTApp looks like this: <domain>/rest-api/<addonName>/<restAppRoute>

A simple index.js:

(function() {
   'use strict';

   var router = require('router');

   router.get('/', function(req, res) {
      res.json({message: 'Hello World'});
   });
}());	

Routing

Routes handle how a RESTApp responds requests. The router object provides methods to respond to the following request methods:

  • GET
  • PUT
  • POST
  • DELETE

A route definition has the following structure:

router.method(path, handler);	

Basic examples:

var router = require('router'); // retrieve an instance of the router object

// GET [domain]/rest-api/[headlessCustomModuleName]/user
router.get('/user', function(req, res) {
   res.json({user: 'Robin'});
});

Route parameters

Route parameters are used to capture a value in the URL. Below is an example of a path that will capture userId on the /user route.

// GET [domain]/rest-api/[headlessCustomModuleName]/user/123
router.get('/user/:id', function(req, res) {
 // route is matched and {id: 123} will be populated in the req.params object
});

Request object (req)

The req object is a representation of the HTTP-request.

Properties

req.params

Object that contains parameters passed to a route. The object contains route parameters ('/user/:userId'), query string parameters and values in the request body from POST, PUT and DELETE.

// GET [domain]/rest-api/[headlessCustomModuleName]/user/456
router.get('/user/:userId', function(req, res) {
   logger.info(req.params.userId); // 456
});
// GET [domain]/rest-api/[headlessCustomModuleName]/user?foo=bar
router.get('/user', function(req, res) {
   logger.info(req.params.foo); // bar
});
// POST [domain]/rest-api/[headlessCustomModuleName]/addToBasket (productId=1)
router.post('/addToBasket', function(req, res) {
   logger.info(req.params.productId); // 1
});

req.files

Object containing files (java.io.File) from a multi-part request.

router.post('/', function(req, res) {
   var myFile = req.files.name;
});

req.cookies

Object that contains cookies from the request.

// Cookie basketId=789
router.get('/user', function(req, res){
   logger.info(req.cookies.basketId); // 789
});

req.xhr

Boolean indicating whether or not the request is an XHR (ajax) request.

router.get('/', function(req, res) {
   if (req.xhr) {
      res.json({foo: 'ajax-bar'});
   } else {
      res.json({foo: 'bar'});
   }
});	

req.session

Session data is stored and accessed through the req.session property. Session attributes are namespaced for WebApps/RESTapps, i.e. "global" session attributes cannot be accessed. Note that session data must be JSON serializable.

// WebApp/RESTApp x
router.get('/', function(req, res) {
   req.session.name = 'John Doe';
});
// WebApp/RESTApp y
router.get('/', function(req, res) {
   logger.info(req.session.name); // 'John Doe';
});

Methods

req.invalidateSession()

Invalidates current session.

Response object (res)

The res object is a representation of the HTTP-response.

Methods

res.set(name, value)

Sets a HTTP-header in the response. Returns this for chaining purposes.

res.set('Content-Type', 'application/json');

res.send(response)

Sends a text/html-response.

res.send('Hello from RESTApp!');

res.json(response)

Sends a application/json-response.

res.json({
   id: '123',
   foo: 'bar'
});

res.sendFile(file)

Sends a file as response. Uses best effort for content type matching. File argument must be a java.io.File or a SiteVision JCR-Node (sv:file or sv:image).

res.sendFile(file);

res.status(code)

Sets the HTTP-status for the response. Returns this for chaining purposes.

res.status(404).send('Not found');

res.cookie(object)

Adds a cookie. The cookie is set with httpOnly = false and path = '/'.

res.cookie({
   name: 'basketId',
   value: '123'
});

res.clearCookie(name [, path])

Clears a cookie given a name. If path is missing, it defaults to '/'.

res.clearCookie('basketId');