1.0.17 • Published 5 years ago

swizi-forms-sdk v1.0.17

Weekly downloads
1
License
MIT
Repository
gitlab
Last release
5 years ago

Swizi forms SDK

This SDK allows to use Swizi Forms service from js plugin. The library manages a cache using Swizi file storage. With this library it is possible to build plugin with offline mode. Create and update query can be store to be executed later if network is not available.

Summary

  1. Installation
  2. Usage
  3. Debug considerations
  4. API
  5. Tutorial - English
  6. Tutoriel - Français

Installation

npm i swizi-forms-sdk

or

yarn add swizi-forms-sdk

A complete example of usage is available on gitlab : https://gitlab.com/Swizi/swizi-community/swizi-offline-plugin

Usage

To use the SDK you need an API key and a secret key to connect to form server. This API key is provided with your Swizi Subscription.

To use library with local storage for debug purpose :

import FormsSdk from 'swizi-forms-sdk'
const FormsClient = FormsSdk.FormsClient

let formClient = FormsClient.fromLocalStorage(myApiKey, mySecretKey, formsServerAddress, localStorageKey)

localStorageKey is the key where data are stored

To use library in a Swizi Plugin :

 import FormsSdk from 'swizi-forms-sdk'
 const FormsClient = FormsSdk.FormsClient

 let formClient = FormsClient.fromSwizi(keyGroup)

keyGroup is the name of a key value group. You must configure plugin to provide keys : apikey, secretkey and server

Debug considerations

This library uses debug package. To display debug information add environment variable : DEBUG=FormsClient:* To display debug information from Swizi add a key name "DEBUG" to keyGroup

Events

It is possible to listen to event from SDK. To do it, use addListener method to pass a callback.

callback prototype is

callback([queriesOrViews], eventType, datas)

queriesOrViews is an array of string containing the names of queries and/or views concerned by event. eventType is a code from static variable FormsClient.events datas is the results given by the server when adding or updating datas.

Event CodePurpose
QUERY_FAILEDA query failed to execute on form server. ie server is reachable and return code is different from http 200
QUERY_SUCCESSA query was executed with success. Form service returned http 200 code. If it is a refresh or add query, cache has been updated and it is possible do retrieve data from getData('queryName') method.
QUERY_DELAYEDA query can't be executed because of network failure or timeout. The query has been store in queue and will be executed later.
FETCH_STARTEDA request to server has just started. Useful to display spinner during request execution.
FETCH_STOPPEDA request to server has just stopped. Useful to display spinner during request execution.

API

API Documentation for Forms SDK is available here: https://ms-desk.swizi.io/doc/Forms_Client_SDK_for_JS/ API Documentation for Forms service is available here : https://ms-desk.swizi.io/doc/Forms/

Swizi Forms SDK Tutorial

Introduction

Swizi Forms SDK is a javascript library that allows you to use the Forms service from a Swizi plugin. The library supports calls to the service and the management of a local cache which allows to keep a state of the data including in situation of network loss (offline mode).

Requirements and installation

To use the Swizi Forms SDK library it is necessary to have access to the Forms service and the associated connection credentials : API Key and Secret Key.

The forms (tables) must have been previously created.

The SDK is available on npm

npm i swizi-forms-sdk

or

yarn add swizi-forms-sdk

SDK usage

import FormsSdk from 'swizi-forms-sdk'
const FormsClient = FormsSdk.FormsClient

How does it work ?

This library allows to create an interface with the Forms service by permanently storing the last state of the data locally. Update requests are stacked in a queue until they are properly executed. Data and queries are stored via the Swizi.js SDK in the Realm database of the Swizi mobile application.

When the SDK is used in development mode in a Chrome browser (outside a mobile application) the data is stored in the localstorage.

To understand how the SDK works, you need to understand the following concepts:

  • Views The views correspond to the data associated with a Form after applying a filter. (find query). A view on the Form "User" and with the filter"{age: {$gte: 20}}" corresponds to all records of the Form User for which the user is more than 20 years old.

  • The cache The cache is a local storage of the view data configured in the Swizi Forms client as well as a storage of unexecuted requests.

  • The queue The queue contains a list of queries that have not yet been executed on views. The queue is stored in the cache so that it can be executed later if necessary. Every 10 seconds, the SDK tries to unstack the line. A request is deleted from the queue after receiving the http 200 code from the Forms service.

Demonstration account

For this tutorial, we use a Swizi Forms demo account. This demo account contains a single Form called "SampleForm" it contains two string fields: field and value.

Credentials are below :

apikey = n5exdAZP3SfNkMU2rHKPs5Zbq1Tqxq1vAFrZHQ16
secretkey = Z4dCFwzkxUxfB2E35CUWQc0Gp

Create a Swizi Forms client

When creating a Swizi Forms client, the following sequence is started:

  1. Loading data from locally stored views
  2. Launch a refresh request for each view
  3. Launch any pending requests in the queue that was stored in the cache

    Creation from a Swizi App

  • Create a key/value data type connector
  • Create an "apikey" key with the Forms Service Key API value
  • Create a "secretkey" key with the value of the Forms Service Secret Key
  • Create a server key with the API url of the forms service to use
  • Optional: if you want to have debug information in the Swizi console of the player, add a DEBUG key with the value true

npm.io

The creation of the client is done with the connector name :

FormsClient
    .fromSwizi('forms')
    .then(formsClient=>{...})
    .catch(e=>{...})

Creation from localstorage Plugins are usually tested on a Chrome browser outside the mobile App during the development phase. It is possible to simulate SDK behavior by using the browser localstorage as the storage location.

// Create form client
if (_DEV_)
  promise = FormsClient.fromLocalStorage('n5exdAZP3SfNkMU2rHKPs5Zbq1Tqxq1vAFrZHQ16', 'Z4dCFwzkxUxfB2E35CUWQc0Gp', 'https://ms-forms.swizi.io', 'formsSDKTest')
else
  promise = FormsClient.fromSwizi('forms')

promise
.then(formsClient=>{...})
.catch(e=>{...})

Create a view

Creating a view consists in defining the name of the view and the filter to apply. In the following example, we create a view on the Form SampleForm without filter.

if (!formsClient.exists('myView'))
	  formsClient.createView('myView', 'SampleForm', {})

Generally, the first time you use it you want to create a view and the next times just refresh it. For this, the createOrRefreshView method can be used.

Ask a view to be refreshed

The data in a view is refreshed only on request in the following way:

if (formsClient.exists('myView'))
	  formsClient.refreshView('myView')

The refresh request is added to the queue. If a refresh request is already present in the queue for this view, the last request is ignored.

Accessing data in a view

The content of a view is accessible as a table containing the JSON objects of Forms

let data = []
if (formsClient.exists('myView'))
	data = formsClient.getData('myView')

Create / edit a record in a view

You can create or edit a record in a view. In this case, an add or update request will be added to the queue.

// Add a new record
formsClient
    .createRecord('A name to identify create request', 'myView', {field: '1', value: 'ABCD'})
    .then(()=>{...})
    .catch(e=>{...})

// Update a existing record
formsClient
    .updateRecord('A name to identify update request', 'myView', {field: '1'}, {value: 'EFGH'})
    .then(()=>{...})
    .catch(e=>{...})

Warning: the views are not automatically refreshed after a record creation or a record update. The initiative of the refresh is left to the developer.

Temporarily hide a record

It may be necessary to hide a record in a view to ensure that it is no longer visible to the user even if the application is disconnected. The filter has an effect on the current cache. At the next refresh the filter will no longer be active.

// keep all records with firstname equals to john
formsClient.filterView('Names',  {firstname:  'john'},  {})

// keep all records with firstname equals to john and lastname not equals to smith
formsClient.filterView('Names',  {firstname:  'john'},  {lastname:  'smith'})

Get pending requests

It is possible to know which queries are waiting for example to display an indicator to the user.

formsClient.getPendingQuery(FormsClient.queryType.CREATE)
formsClient.getPendingQuery(FormsClient.queryType.UPDATE)

Cancel requests

Queries can be cancelled by removing them from the queue.

formsClient.clearPendingQuery(FormsClient.queryType.UPDATE)

Event Management

It is possible to subscribe to the SDK events to be notified of the execution of the different requests.

formsClient.addListener(handleSDKEvent)

function handleSDKEvent(queryOrViewNames, eventType) {
  switch (eventType) {
	  case FormsClient.events.QUERY_SUCCESS:
		  console.log(queryOrViewNames + ' was a success/ May be I should refresh my view ... ')
	  break;
	  case FormsClient.events.QUERY_DELAYED:
		  console.log(queryOrViewNames + ' was added to queue ')
	  break;
	  case FormsClient.events.FETCH_STARTED:
		  console.log('A request is starting, should I display a spinner ?')
	  break;
	  case FormsClient.events.FETCH_STOPPED:
		  console.log('A request is starting, should I hide my spinner ?')
	  break;
  }
}

Example

An example plugin is available on GitLab : https://gitlab.com/Swizi/swizi-community/forms-sdk-demo

This allows you to create/update data in the sample Form in this tutorial. The configuration to use and the one indicated in the installation chapter.

To see the offline modes, switch the smartphone to aircraft mode and add/modify records.

Tutoriel Swizi Forms SDK

Introduction

Swizi Forms SDK est une librairie javascript qui permet d'utiliser le service Forms depuis un plugin Swizi. La librairie prend en charge les appels au service et la gestion d'un cache local qui permet de conserver un état des données y compris en situation de perte de réseau.

Pré requis et installation

Pour utiliser la librairie Swizi Forms SDK il est nécessaire de disposer un accès au service Forms et les éléments de connexion associés : API Key et Secret Key.

Les forms (tables) doivent avoir été créées au préalable.

Le SDK est disponible sur npm via la commande

npm i swizi-forms-sdk

ou

yarn add swizi-forms-sdk

Import du SDK

import FormsSdk from 'swizi-forms-sdk'
const FormsClient = FormsSdk.FormsClient

Principe de fonctionnement

Cette librairie permet de créer une interface avec le service Forms en stockant en permanence le dernier état des données en local. Les requêtes de mises à jour sont empilées dans une file d'attente jusqu'à ce qu'elles soient correctement exécutées. Les données et les requêtes sont stockées via le SDK Swizi.js dans la base Realm de l'application mobile Swizi.

Lorsque le SDK est utilisé en mode développement dans un navigateur Chrome (hors application mobile) les données sont stockées dans le localstorage.

Pour comprendre le fonctionnement du SDK il faut assimiler les concepts suivants :

  • Les vues (View) Les vues correspondent aux données associées à une Form après application d'un filtre. (requête find). Une vue sur la Form "User" et avec le filtre "{age: {$gte: 20}}" correspond à tous les enregistrements de la Form User pour lesquels l'utilisateur a plus de 20 ans.

  • Le cache Le cache est un stockage local des données des vues configurées dans le client Swizi Forms ainsi qu'un stockage des requêtes non exécutées.

  • La file d'attente (Queue) La file d'attente contient une liste de requêtes qui n'ont pas encore été exécutées sur les vues. La file d'attente est stockée dans le cache pour pouvoir être exécutée ultérieurement si besoin. Toutes les 10 secondes, le SDK tente de dépiler la file. Une requête est supprimée de la file après réception du code http 200 du service Forms.

Compte de démonstration

Pour ce tutoriel, nous utilisons un compte de démonstration Swizi Forms. Ce compte de démonstration contient une seule Form appelée "SampleForm" elle contient deux champs de type "string" : field et value.

Les informations de connexion sont les suivantes :

apikey = n5exdAZP3SfNkMU2rHKPs5Zbq1Tqxq1vAFrZHQ16
secretkey = Z4dCFwzkxUxfB2E35CUWQc0Gp

Créer un client Swizi Forms

Lors de la création d'un client Swizi Forms, la séquence suivante est lancée :

  1. Chargement des données des vues stockées localement
  2. Lancement d'une requête de rafraîchissement de chaque vue
  3. Lancement des éventuelles requêtes en attente dans la file d'attente qui était stockée dans le cache

    Création depuis une App Swizi

  • Créez un connecteur de type données clé/valeur
  • Créez une clé "apikey" avec la valeur de l'API Key du service Forms
  • Créez une clé "secretkey" avec la valeur du Secret Key du service Forms
  • Créez une clé "server" avec l'url de l'API du service forms à utiliser
  • Optionnel : si vous souhaitez avoir des informations de type debug dans la console Swizi du player, ajoutez une clé DEBUG avec la valeur true

npm.io

La création du client est fait via le nom du connecteur :

FormsClient
    .fromSwizi('forms')
    .then(formsClient=>{...})
    .catch(e=>{...})

Création depuis le localstorage Les plugin sont généralement testés sur un navigateur Chrome en dehors de l'App mobile durant la phase de développement. Il est possible de simuler le comportement du SDK en utilisant le localstorage du navigateur comme lieu de stockage.

// Create form client
if (_DEV_)
  promise = FormsClient.fromLocalStorage('n5exdAZP3SfNkMU2rHKPs5Zbq1Tqxq1vAFrZHQ16', 'Z4dCFwzkxUxfB2E35CUWQc0Gp', 'https://ms-forms.swizi.io', 'formsSDKTest')
else
  promise = FormsClient.fromSwizi('forms')

promise
.then(formsClient=>{...})
.catch(e=>{...})

Créer une vue

La création d'une vue consiste à définir le nom de la vue et le filtre à appliquer. Dans l'exemple suivant, on crée une vue sur la Form SampleForm sans filtre.

if (!formsClient.exists('myView'))
	  formsClient.createView('myView', 'SampleForm', {})

Généralement, à la première utilisation on souhaite créer une vue et les fois suivantes juste la rafraîchir. Pour cela, la méthode createOrRefreshView peut être utilisée.

Provoquer le rafraichissement d'une vue

Les données d'une vues sont rafraichies uniquement sur demande de la manière suivante :

if (formsClient.exists('myView'))
	  formsClient.refreshView('myView')

La requête de rafraichissement est ajoutée à la file d'attente. Si une requête de rafraichissement est déjà présente dans la file d'attente pour cette vue, la dernière demande est ignorée.

Accéder aux données d'une vue

Le contenu d'une vue est accessible sous forme de tableau contenant les objets JSON de Forms

let data = []
if (formsClient.exists('myView'))
	data = formsClient.getData('myView')

Créer / modifier un enregistrement dans une vue

Il est possible de créer ou modifier un enregistrement dans une vue. Dans ce cas, un requête add ou update sera ajoutée à la file d'attente.

// Add a new record
formsClient
    .addRecord('A name to identify create request', 'myView', {field: '1', value: 'ABCD'})
    .then(()=>{...})
    .catch(e=>{...})

// Update a existing record
formsClient
    .updateRecord('A name to identify update request', 'myView', {field: '1'}, {value: 'EFGH'})
    .then(()=>{...})
    .catch(e=>{...})

Attention : les vues ne sont pas automatiquement rafraîchies après création ou modification d'un enregistrement. L'initiative du rafraîchissement est laissé au développeur.

Temporairement masquer un enregistrement

Il peut être nécessaire de masquer un enregistrement dans une vue pour s'assurer qu'il n'est plus visible de l'utilisateur même si l'application est déconnectée. Le filtre a un effet sur le cache en cours. Au prochain rafraîchissement le filtre ne sera plus actif.

// keep all records with firstname equals to john
formsClient.filterView('Names',  {firstname:  'john'},  {})

// keep all records with firstname equals to john and lastname not equals to smith
formsClient.filterView('Names',  {firstname:  'john'},  {lastname:  'smith'})

Connaître les requêtes en attente

Il est possible de connaître les requêtes en attente par exemple pour afficher un indicateur à l'utilisateur.

formsClient.getPendingQuery(FormsClient.queryType.CREATE)
formsClient.getPendingQuery(FormsClient.queryType.UPDATE)

Annuler une requête

Il est possible d'annuler des requêtes en les supprimant de la file d'attente.

formsClient.clearPendingQuery(FormsClient.queryType.UPDATE)

Gestion des évènements

Il est possible de s'abonner aux évènements du SDK pour être notifié de l'exécution des différentes requêtes.

formsClient.addListener(handleSDKEvent)

function handleSDKEvent(queryOrViewNames, eventType) {
  switch (eventType) {
	  case FormsClient.events.QUERY_SUCCESS:
		  console.log(queryOrViewNames + ' was a success/ May be I should refresh my view ... ')
	  break;
	  case FormsClient.events.QUERY_DELAYED:
		  console.log(queryOrViewNames + ' was added to queue ')
	  break;
	  case FormsClient.events.FETCH_STARTED:
		  console.log('A request is starting, should I display a spinner ?')
	  break;
	  case FormsClient.events.FETCH_STOPPED:
		  console.log('A request is starting, should I hide my spinner ?')
	  break;
  }
}

Exemple

Un plugin exemple est disponible sur GitLab : https://gitlab.com/Swizi/swizi-community/forms-sdk-demo

Celui-ci permet de créer / mettre à jour des données dans la Form exemple de ce tuto. La configuration à utiliser et celle indiquée dans le chapitre installation.

Pour constater les mode off line, mettez le smartphone en mode avion et ajoutez/modifiez des enregistrement.

1.0.17

5 years ago

1.0.16

5 years ago

1.0.15

5 years ago

1.0.14

6 years ago

1.0.13

6 years ago

1.0.10

6 years ago

1.0.9

6 years ago

1.0.8

6 years ago

1.0.7

6 years ago

1.0.6

6 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago