Skip to main content

Storing Key-Value Data

This section describes how to use sos.offline.cache API.

The sos.offline.cache API provides methods for caching files and storing key-value data. It is similar to HTML5 localStorage, but it is implemented on all devices and is device-agnostic. It also does not have the limitations of localStorage, such as:

  • localStorage has limited storage size (5MB)
  • localStorage is shared between applets

The sos.offline.cache object provides four methods for managing key-value data: loadContent(), saveContent(), listContents(), and deleteContent().

The API for storing keys and values can be used to store information that needs to be preserved after a reboot. For example, if the applet needs to download a file at a certain interval and maintain that interval even if the device reboots.

import sos from '@signageos/front-applet';

const INTERVAL_MS = 10_000;
const KEY = 'data-last-updated';

sos.onReady(async () => {
// get the timestamp of the last update
const lastUpdated = await sos.offline.cache
.loadContent(KEY)
.then((v) => Number(v))
.catch(() => 0);

const now = Date.now();

// calculate the time remaining until the next update
const remainingTime = Math.max(0, now - lastUpdated);

setTimeout(loop, remainingTime);
});

async function loop() {
// Update the data
await sos.offline.cache.deleteFile('data.json');
await sos.offline.cache.saveFile('data.json', 'http://example.com');

// Save the current time
await sos.offline.cache.saveContent(KEY, String(Date.now()));

console.log('data.json was updated');

// Continue the loop in scheduled interval
setTimeout(loop, INTERVAL_MS);
}