Making your first session app using enigma.js

Overview

In this tutorial, you are going to learn how to use session apps in Qlik Sense SaaS. Are you new to the concept of session apps? Read more about session apps before continuing.

If you’re just interested in the code produced in this tutorial, skip to the Summary section.

Requirements

  • An API key from your tenant
  • Node.js (version 10 or newer)
  • A terminal (for example Git Bash on Windows, or Terminal.app on Mac)
  • A text editor or IDE of your choice, for example, Visual Studio Code

Define your load script

Note: Since session apps are created on the fly and require a data reload, they benefit from small data models. For an optimal experience, make sure your load script does not load too much data or the end-user experience may suffer.

If you already have a load script in mind, feel free to skip this section. Otherwise, here’s one that doesn’t require any external data source.

TempTable:
  Load
    RecNo() as ID,
    Rand() as Value
  AutoGenerate 100

Opening a session

Move into a new empty folder in your terminal, and run npm install enigma.js ws. This installs the npm dependencies needed for this tutorial.

After dependencies are installed, create a new file in the same folder using your IDE and call it session-app.js.

In the file, start by loading the npm dependencies:

const enigma = require('enigma.js');
const schema = require('enigma.js/schemas/12.612.0');
const WebSocket = require('ws');

Note: In Qlik Cloud, the methods CreateSessionApp and CreateSessionAppFromApp aren’t used, instead the API is URL-based.

Next up is to make the websocket URL, which is an important step when working with session apps. The app ID needs to be prefixed with SessionApp_. It also needs to contain a unique identifier.

Place and update these variables at the end of your file:

(async () => {
  const randomId = Math.random().toString(32).substring(3);
  const appId = `SessionApp_${randomId}`;
  const tenant = '<your-tenant.qlikcloud.com>';
  const apiKey = '<your-api-key>';
  const url = `wss://${tenant}/app/${appId}`;
  const script = `
TempTable:
  Load
    RecNo() as ID,
    Rand() as Value
  AutoGenerate 100
  `;
})();

Note: The (async () => {})(); piece is just so that you can use the async and await syntax directly inside the file without calling a function.

The script so far has imported all dependencies and defined all the variables you need to actually open a websocket connection and start working with the session app.

The snippet below shows how to:

Add this at the end of your script, preceding the })(); line:

  const session = enigma.create({
    schema,
    createSocket: () =>
      new WebSocket(url, {
        // use the API key to authenticate:
        headers: { Authorization: `Bearer ${apiKey}` },
      }),
  });

  try {
    const global = await session.open();
    const app = await global.getActiveDoc();
    await app.setScript(script);
    await app.doReload();
  } catch (err) {
    console.log('An unexpected error thrown:', err);
  }

  session.close();

Great, you now have a session app all ready to evaluate expressions, build hypercubes, and much more. If you don’t want to close the session, omit the last line. In this next code piece, you’ll evaluate an expression just to verify that the data was loaded successfully.

After the app.doReload() line, add this:

    const result = await app.evaluate('COUNT([Value])');
    if (result !== '100') {
      throw new Error(`Expected expression to equal 100: ${result}`);
    } else {
      console.log('Success! 100 lines were loaded and evaluated.');
    }

If you haven’t done so already, try running the complete script in your terminal:

node session-app.js

Summary

This is a short tutorial that shows you how to create a script using enigma.js to:

  • open a session app
  • set a load script and load data in-memory
  • evaluate a simple expression

You can continue working on this script and do more complex things like using listobjects and hypercubes. You can find more examples to get you started in the enigma.js git repository.

session-app.js

const enigma = require('enigma.js');
const schema = require('enigma.js/schemas/12.612.0');
const WebSocket = require('ws');

(async () => {
  const randomId = Math.random().toString(32).substring(3);
  const appId = `SessionApp_${randomId}`;
  const tenant = '<your-tenant.qlikcloud.com>';
  const apiKey = '<your-api-key>';
  const url = `wss://${tenant}/app/${appId}`;
  const script = `
TempTable:
  Load
    RecNo() as ID,
    Rand() as Value
  AutoGenerate 100
  `;

  const session = enigma.create({
    schema,
    createSocket: () =>
      new WebSocket(url, {
        // use the API key to authenticate:
        headers: { Authorization: `Bearer ${apiKey}` },
      }),
  });

  try {
    const global = await session.open();
    const app = await global.getActiveDoc();
    await app.setScript(script);
    await app.doReload();
    const result = await app.evaluate('COUNT([Value])');
    if (result !== '100') {
      throw new Error(`Expected expression to equal 100: ${result}`);
    } else {
      console.log('Success! 100 lines were loaded and evaluated.');
    }
  } catch (err) {
    console.log('An unexpected error thrown:', err);
  }

  session.close();
})();

Was this page helpful?