RemoteStorage

Constructor

Create a remoteStorage class instance like so:

const remoteStorage = new RemoteStorage();

The constructor can optionally be called with a configuration object. This example shows all default values:

const remoteStorage = new RemoteStorage({
  cache: true,
  changeEvents: {
    local:    true,
    window:   false,
    remote:   true,
    conflict: true
  },
  cordovaRedirectUri: undefined,
  logging: false,
  modules: []
});

Note

In the current version, it is only possible to use a single RemoteStorage instance. You cannot connect to two different remotes yet. We intend to support this eventually (see issue #991)

Warning

For the change events configuration, you currently have to set all events explicitly. Otherwise it would disable the unspecified ones. (see issue #1025)

Events

You can handle events from your remoteStorage instance by using the .on() function. For example:

remoteStorage.on('connected', function() {
  // Storage account has been connected, let’s roll!
});

List of events

ready

Emitted when all features are loaded and the RS instance is ready

not-connected

Emitted when ready, but no storage connected (“anonymous mode”)

connected

Emitted when a remote storage has been connected

disconnected

Emitted after disconnect

error

Emitted when an error occurs; receives an error object as argument

There are a handful of known errors, which are identified by the name property of the error object:

Name

Description

Unauthorized

Emitted when a network request resulted in a 401 or 403 response. You can use this event to handle invalid OAuth tokens in custom UI (i.e. when a stored token has been revoked or expired by the RS server).

DiscoveryError

A variety of storage discovery errors, e.g. from user address input validation, or user address lookup issues

Example:

remoteStorage.on('error', err => console.log(err));

// {
//   name: "Unauthorized",
//   message: "App authorization expired or revoked.",
//   stack: "Error↵  at new a.Unauthorized (vendor.js:65710:41870)"
// }

features-loaded

Emitted when all features are loaded

connecting

Emitted before webfinger lookup

authing

Emitted before redirecting to the authing server

wire-busy

Emitted when a network request starts

wire-done

Emitted when a network request completes

sync-req-done

Emitted when a single sync request has finished. Callback functions receive an object as argument, informing the client of remaining items in the current sync task queue.

Example:

remoteStorage.on('sync-req-done', result => console.log(result));

// { tasksRemaining: 21 }

Note

The internal task queue holds at most 100 items at the same time, regardless of the overall amount of items to sync. Therefore, this number is only an indicator of sync status, not a precise amount of items left to sync. It can be useful to determine if your app should display any kind of sync status/progress information for the cycle or not.

sync-done

Emitted when a sync cycle has been completed and a new sync is scheduled.

The callback function receives an object as argument, informing the client if the sync process has completed successfully or not.

Example:

remoteStorage.on('sync-done', result => console.log(result));

// { completed: true }

If completed is false, it means that some of the sync requests have failed and will be retried in the next sync cycle (usually a few seconds later in this case). This is not an unusual scenario on mobile networks or when doing a large initial sync for example.

For an app’s user interface, you may want to consider the sync process as ongoing in this case, and wait until your app sees a positive completed status before updating the UI.

network-offline

Emitted once when a wire request fails for the first time, and remote.online is set to false

network-online

Emitted once when a wire request succeeds for the first time after a failed one, and remote.online is set back to true

sync-interval-change

Emitted when the sync interval changes

List of functions

The following methods/functions can be called on your remoteStorage instance:

connect(userAddress[, token])

Connect to a remoteStorage server.

Discovers the WebFinger profile of the given user address and initiates the OAuth dance.

This method must be called after all required access has been claimed. When using the connect widget, it will call this method itself.

Special cases:

  1. If a bearer token is supplied as second argument, the OAuth dance will be skipped and the supplied token be used instead. This is useful outside of browser environments, where the token has been acquired in a different way.

  2. If the Webfinger profile for the given user address doesn’t contain an auth URL, the library will assume that client and server have established authorization among themselves, which will omit bearer tokens in all requests later on. This is useful for example when using Kerberos and similar protocols.

Arguments:
  • userAddress (string) – The user address (user@host) or URL to connect to.

  • token (string) – (optional) A bearer token acquired beforehand

Example:

remoteStorage.connect('user@example.com');
disconnect()

“Disconnect” from remote server to terminate current session.

This method clears all stored settings and deletes the entire local cache.

Example:

remoteStorage.disconnect();
enableLog()

TODO: do we still need this, now that we always instantiate the prototype?

Enable remoteStorage logging.

Example:

remoteStorage.enableLog();
disableLog()

TODO: do we still need this, now that we always instantiate the prototype?

Disable remoteStorage logging

Example:

remoteStorage.disableLog();
getSyncInterval()

Get the value of the sync interval when application is in the foreground

Returns:

number – A number of milliseconds

Example:

remoteStorage.getSyncInterval();
// 10000
setSyncInterval(interval)

Set the value of the sync interval when application is in the foreground

Arguments:
  • interval (number) – Sync interval in milliseconds (between 2000 and 3600000 [1 hour])

Example:

remoteStorage.setSyncInterval(10000);
getBackgroundSyncInterval()

Get the value of the sync interval when application is in the background

Returns:

number – A number of milliseconds

Example:

remoteStorage.getBackgroundSyncInterval();
// 60000
setBackgroundSyncInterval(interval)

Set the value of the sync interval when the application is in the background

Arguments:
  • interval (number) – Sync interval in milliseconds (between 2000 and 3600000 [1 hour])

Example:

remoteStorage.setBackgroundSyncInterval(60000);
getCurrentSyncInterval()

Get the value of the current sync interval. Can be background or foreground, custom or default.

Returns:

number – A number of milliseconds

Example:

remoteStorage.getCurrentSyncInterval();
// 15000
getRequestTimeout()

Get the value of the current network request timeout

Returns:

number – A number of milliseconds

Example:

remoteStorage.getRequestTimeout();
// 30000
setRequestTimeout(timeout)

Set the timeout for network requests.

Arguments:
  • timeout (number) – Timeout in milliseconds

Example:

remoteStorage.setRequestTimeout(30000);
scope(path)

This method enables you to quickly instantiate a BaseClient, which you can use to directly read and manipulate data in the connected storage account.

Please use this method only for debugging and development, and choose or create a data module for your app to use.

Arguments:
  • path (string) – The base directory of the BaseClient that will be returned (with a leading and a trailing slash)

Returns:

BaseClient – A client with the specified scope (category/base directory)

Example:

remoteStorage.scope('/pictures/').getListing('');
remoteStorage.scope('/public/pictures/').getListing('');
setApiKeys(apiKeys)

Set the OAuth key/ID for either GoogleDrive or Dropbox backend support.

Arguments:
  • apiKeys (<TODO: reflection>) – A config object with these properties:

Returns:

void|boolean

Example:

remoteStorage.setApiKeys({
  dropbox: 'your-app-key',
  googledrive: 'your-client-id'
});
setCordovaRedirectUri(uri)

Set redirect URI to be used for the OAuth redirect within the in-app-browser window in Cordova apps.

Arguments:
  • uri (string) – A valid HTTP(S) URI

Example:

remoteStorage.setCordovaRedirectUri('https://app.wow-much-app.com');
startSync()

Start synchronization with remote storage, downloading and uploading any changes within the cached paths.

Please consider: local changes will attempt sync immediately, and remote changes should also be synced timely when using library defaults. So this is mostly useful for letting users sync manually, when pressing a sync button for example. This might feel safer to them sometimes, esp. when shifting between offline and online a lot.

Returns:

Promise<void> – A Promise which resolves when the sync has finished

Example:

remoteStorage.startSync();
stopSync()

Stop the periodic synchronization.

Example:

remoteStorage.stopSync();
on(eventName, handler)

Example:

remoteStorage.on('connected', function() {
  console.log('user connected their storage');
});
onChange(path, handler)

Add a “change” event handler to the given path. Whenever a “change” happens (as determined by the backend, such as e.g. <RemoteStorage.IndexedDB>) and the affected path is equal to or below the given ‘path’, the given handler is called.

You should usually not use this method directly, but instead use the “change” events provided by BaseClient

Arguments:
  • path (string) – Absolute path to attach handler to

  • handler (any) – Handler function

Example:

remoteStorage.onChange('/bookmarks/', function() {
  // your code here
})