Skip to main content

latest
Works with
JSR Score
47%
Published
3 months ago (5.6.5)

title: Readme

@soleil-api/webapp-util@^5.0.0

Utility functions for WebApps.

GitHub
NPM

[[toc]]

Requirements

  • Sitevision 9.1.0 or later.
  • @soleil/sv-app-build@^1.0.0 or @sitevision/sitevision-scripts@^3.0.0.
  • WebApps 2 enabled app.

Manifest

bundled needs to be enabled in WebApp manifest for WebApps 2.

{
  "id": "se.soleil.myApp",
  "version": "1.0.0",
  "name": "My app",
  "author": "Soleil AB",
  "description": "",
  "helpUrl": "https://soleil.se/support",
  "type": "WebApp",
  "bundled": true
}

Install

> npm install @soleil-api/webapp-util
> yarn add @soleil-api/webapp-util

:::details Integrity check failed If the following error occurs when installing with Yarn run yarn install --update-checksums.

Integrity check failed for "@soleil-api/webapp-util" (computed integrity doesn...

:::

Migration

Migrating from version 4?
See MIGRATION.

Common

All imports from base package are available both on the server and client.

appId : String

DOM friendly unique identifier for the WebApp.

import { appId } from '@soleil-api/webapp-util';

console.log(appId); // For example: 12_682d461b1708a9bb1ea13efd

isOffline : Boolean

If the WebApp is running in offline mode or not.

import { isOffline } from '@soleil-api/webapp-util';

console.log(isOffline);  // true or false

isOnline : Boolean

If the WebApp is running in online mode or not.

import { isOnline } from '@soleil-api/webapp-util';

console.log(isOnline); // true or false

isServer : Boolean

If the current code is running on the server.

import { isServer } from '@soleil-api/webapp-util';

console.log(isServer); // true or false

isBrowser : Boolean

If the current code is running in the browser.

import { isBrowser } from '@soleil-api/webapp-util';

console.log(isBrowser); // true or false

getNamespace([prefix]) ⇒ String

Get a prefixed namespace unique for app.

Returns: String - Prefixed namespace.

Param Type Default
[prefix] string "'app'"
import { getNamespace } from '@soleil-api/webapp-util';

console.log(getNamespace());
// For example: app_12_682d461b1708a9bb1ea13efd

console.log(getNamespace('input'));
// For example: input_12_682d461b1708a9bb1ea13efd

// If the app is in a decoration template the Portlet ID is the same for all instances, so the ID of the decorated node is used as well.
console.log(getNamespace('decoration'));
// For example: decoration_10_3871c02f1754f3aa8f9d4eb_12_70c3d424173b4900fc550e1c

generateId([prefix]) ⇒ String

Generate a unique identifier with a random UUID without dashes.

Returns: String - Unique identifier.

Param Type Default
[prefix] string "'id'"
import { generateId } from '@soleil-api/webapp-util';

console.log(generateId());
// For example: id_550e8400e29b41d4a716446655440000

console.log(generateId('input'));
// For example: input_550e8400e29b41d4a716446655440000

getRouteUri(route, [query]) ⇒ String

Get URI for a route.

Returns: String - URI for route.

Param Type Description
route String A route.
query Object Object with query string parameters
import { getRouteUri } from '@soleil-api/webapp-util';

console.log(getRouteUri('/items'));
// URI structure: /appresource/{pageId}/{portletId}>/items
import { getRouteUri } from '@soleil-api/webapp-util';

console.log(getRouteUri('/items', { foo: 'bar' }));
// URI structure: /appresource/{pageId}/{portletId}>/items?foo=bar

getResourceUri(resource) ⇒ String

Get URI for a resource.

Returns: String - URI for a resource.

Param Type Description
resource String A resource.
import { getResourceUri } from '@soleil-api/webapp-util';

console.log(getResourceUri('/image.png'));
// URI structure: /webapp-files/<webappname>/<webappversion>/image.png

getAppProps([key]) ⇒ * | Object

Get props that are passed to app when rendering.

Returns: * | Object - Value or object.

Param Type Description
[key] String Key for value.
import { getAppProps } from '@soleil-api/webapp-util';

// Get value with key
const myValue = getAppProps('myValue');
// Or with destructuring
const { myValue } = getAppProps();

stringifyParams(params [, options]) ⇒ String

Stringify an object to a query string compatible with Sitevision.

Returns: String - Stringified parameters.

Param Type Default Description
params Object Object with parameters to stringify.
[options] Object {} Options object.
[options.addQueryPrefix] Boolean false If a leading ? should be added to the string.
import { stringifyParams } from '@soleil-api/webapp-util';

const queryString = stringifyParams({ foo: 'bar', num: 1 });
// foo=bar&num=1

const queryString = stringifyParams({ foo: 'bar', num: 1 }, { addQueryPrefix: true });
// ?foo=bar&num=1

parseParams(url) ⇒ Object

Parse an URL, URI or query string to an object containing its query parameters.

Returns: Object - Parsed parameters.

Param Type Default Description
url String URL, URI or query string to be parsed, must start with or contain "?"
import { parseParams } from '@soleil-api/webapp-util';

const params = parseParams('?foo=bar&arr[]=1&arr[]=2');
// { foo: 'bar', arr: [1, 2] }

Client

Following API:s are available in a client context.

Fetch

Fetch wrapper for calling app routes, rest-api or external resources.

fetchJson() => Promise<Object>

Param Type Default Description
uri String URI for resource
[options] Object {} Options object, two custom options rest is standard fetch options
[options.params] Object {} Object with parameters to be appended to the URI
[options.retries] Number 0 Number of retries if the request times out.

Returns: Promise<Object> - Promise containing parsed JSON-data.
Throws Error - Extended error object with custom properties for status, aborted and other JSON-data returned by the request.

URI:s starting with /rest-api, /appresource, /edit-app-config or a protocol, for example https:// will be left as is.
Other URI:s will be converted to match a route in the current app with getRouteUri.

Most common usage is getting data from a route in the current app.

import { fetchJson } from '@soleil-api/webapp-util/client';

async function getItems() {
  const params = { query: 'foo', start: 0, num: 10 };
  const result = await fetchJson('/items', { params });
  console.log(result);
}

Posting form data.

import { fetchJson } from '@soleil-api/webapp-util/client';

async function postForm() {
  const body = new FormData();
  body.append('name', 'Foo');
  body.append('mail', 'foo@bar.com');

  const result = await fetchJson('/create', { method: 'POST', body }));
  console.log(result);
}

Specify number of retries if a request times out.

import { fetchJson } from '@soleil-api/webapp-util/client';

async function getItems() {
  const params = { query: 'foo', start: 0, num: 10 };
  const result = await fetchJson('/items', { params, retries: 5 });
  console.log(result);
}

When searching on input you probably want to abort the ongoing request to avoid weird bugs when the first request might be completed after the subsequent one.
Pass an AbortController signal in options and abort the ongoing call.

import { fetchJson } from '@soleil-api/webapp-util/client';

let controller;

async function onInput() {
  if(controller) controller.abort();
  controller = new AbortController();

  const params = { query: 'foo' };
  try {
    const result = await fetchJson('/search', { params, signal: controller.signal });
    console.log(result);
  } catch(e) {
    // Ignore aborts due to new search.
    if(e.aborted) return;
    // Handle error as usual.
  }
}

URL Parameters

Helper functions setting, getting, updating and clearing query parameters in the URL-field.

getUrlParams() ⇒ Object

Get parameters from the URL-field.

Returns: Object - Parameters in URL-field.

import { getUrlParams } from '@soleil-api/webapp-util/client';

const params = getUrlParams();

getUrlParam() ⇒ String|Array[String]

Get single parameter from the URL-field.

Returns: String|Array[String] - Parameter value.

import { getUrlParam } from '@soleil-api/webapp-util/client';

const param = getUrlParam('name');

setUrlParams(params)

Set parameters in the URL-field, overwriting other parameters.

Param Type Default Description
params Object Object with parameters to set in the URL-field.
import { setUrlParams } from '@soleil-api/webapp-util/client';

setUrlParams({ foo: 'bar', arr: [1, 2] });

updateUrlParams(params)

Update parameters in the URL-field, merging with existing parameters

Returns: String - Stringified parameters.

Param Type Default Description
params Object Object with parameters to add to the URL-field.
import { updateUrlParams } from '@soleil-api/webapp-util/client';

updateUrlParams({ foo: 'bar', arr: [1, 2] });

clearUrlParams()

Clear parameters in the URL-field

import { clearUrlParams } from '@soleil-api/webapp-util/client';

clearUrlParams();

Rendering

Add Package

deno add @soleil/webapp-util

Import symbol

import * as mod from "@soleil/webapp-util";

Add Package

npx jsr add @soleil/webapp-util

Import symbol

import * as mod from "@soleil/webapp-util";

Add Package

yarn dlx jsr add @soleil/webapp-util

Import symbol

import * as mod from "@soleil/webapp-util";

Add Package

pnpm dlx jsr add @soleil/webapp-util

Import symbol

import * as mod from "@soleil/webapp-util";

Add Package

bunx jsr add @soleil/webapp-util

Import symbol

import * as mod from "@soleil/webapp-util";