WebApps 2

index.js

index.js is the server entry point of the WebApp. Use this server side context of the app to collect required data for rendering of the WebApp. Being server side all of the Sitevision Public API is available for use.

router

router is used to set up routing for the WebApp. This enables entry points for GET/POST/PUT/DELETE and PATCH requests in the WebApp as well as middleware.

request

The request (req) object hold information about the request as well as some methods. For example grabbing the request's parameters or invalidating the session.

response

The response (res) object handles the response of the WebApp. Use this to for example send collected data to the client side context of the WebApp to start the rendering processes or setting a cookie.

Example

Let's look at a basic example for a server side context of a WebApp that will display the current page's name and on a button click will fetch the time of the last publish of this page.

// Import needed utilities

// react
import * as React from 'react';
import { renderToString } from 'react-dom/server';

// router to set up routing
import router from '@sitevision/api/common/router';

// Component of the WebApp to render
import App from './components/App';

// Public API utilities
import portletContextUtil from '@sitevision/api/server/PortletContextUtil';
import properties from '@sitevision/api/server/Properties';
import timestampUtil from '@sitevision/api/server/TimestampUtil';
import localeUtil from '@sitevision/api/server/LocaleUtil';

router.get('/', (req, res) => {
   // Fetch current page and it's name
   const page = portletContextUtil.getCurrentPage();
   const name = properties.get(page, 'displayName');

   // Initiate rendering of the WebApp with the name as context
   res.agnosticRender(renderToString(<App name={name} />), {
      name,
   });
});

// Route to collect last publish
router.get('/published', (req, res) => {
   // Fetch current page and the last publish timestamp
   const page = portletContextUtil.getCurrentPage();
   const timestamp = properties.get(page, 'lastPublishDate');

   // Format timestamp to human readable
   const date = timestampUtil.format(
      timestamp,
      'MMMMM yyyy HH:mm:ss',
      localeUtil.getLocaleByString('en')
   );

   // Send the date as JSON
   res.json({
      date,
   });
});

Example result

WebApp displays the current page's name in welcome text. On button click the WebApp will call the /published route to fetch the time of the last publish and pops a toast with the information.

Welcome to index.js!