$a.aex

📘

This section describes methods for working with the Appery.io AppClient.

AppClient is a platform library developed and provided by Appery.io that acts as middleware between the mobile app and Appery.io backend services (API Express and Appery.io Database).
Appery.io backend services can be used directly, so using AppClient in a mobile app is quite optional.

Consider using AppClient with backend services (API Express and Appery.io Database) - it can be very useful while working with apps using a lot of backend services.

AppClient also comes into play when the app requires some advanced features, like, for example, offline mode support and data synchronization, caching, user autologin.

AppClient provides all these and many other useful features out of the box.

Initialization

By default $a.aex helper is not available in the project. To enable this helper you need to provide 2 files:

  • Settings file AppClientSettings
  • External TS lib AppClientMetadata

AppClientSettings

This is a common Settings file (Create New -> Service -> Settings (REST settings)). Available settings are:

PropertyValueDescription
domainhttps://appery.ioServer domain
apiKey65733fc90a975a0123456789Database API Key
currentStateonlineInitial state of AppClient (online or offline). If not specified, default value is online.
handleNetworkStatetrueAllow AppClient to detect network state automatically (true or false). If not specified, default value is true.
cacheTimeout43200Lifetime of cached requests in seconds . If not specified, default value is 43200 (12 hours).
requestTimeout30Number of seconds a request can take before automatically being terminated. If not specified, default value is 30.
autoLogintrueAllow AppClient to login in automatically (true or false). If not specified, default value is true.
clearOnLogoutfalseClear cached user data after logout (true or false). If not specified, default value is false.
version5Version of API Express services (don't change this setting)
backendTargetADBADB (appery.io DB), AEX (API Express) or CUSTOM. If not specified, default value is AEX.
autoSynctrueAllow AppClient to run synchronization automatically (true or false). If not specified, default value is true.

AppClientMetadata

This is a common TypeScript file (Create New -> TypeScript -> Type: External lib).

Example

Here is example for appery.io DB settings

const apiHost = "https://api.appery.io";

const AppClientMetadata = {
    "isSecurity": true,
    "securityOptionsEnabled": true,

    "api": {
        "security": {
          // use custom backend script for login
            "login": {
                "method": "POST",
              // script id is set in Settings -> loginScriptId
                "url": `${apiHost}/rest/1/code/{Settings.loginScriptId}/exec`
            },
          // "loginUserByToken"
          // "login"
          // "logout"
          // "signup"
          // "updateUser"
          // "removeUser"
          // "getCurrentUser"
          // "sessionTokenParamName":"Authorization",
          // "authenticationSchemeName": "Bearer"
          // "apiKeyParamName"
        }
    },

    "models": [
        {
            "modelName": "files",
            "modelType": "BACKEND",
            "modelSyncType": "ONE_WAY",
            "schema": {
                "type": "object",
                "properties": {
                    "_id": {
                        "type": [
                            "string"
                        ]
                    }
                },
                "required": []
            },
            "idAttribute": "_id",
            // "deletedAttribute": "deleted",
            // "modifiedAtAttribute": "_updatedAt",
            "mergeAttributes": ["content"],
            "api": {
                "create": {
                    "url": `${apiHost}/rest/1/db/files`
                },
                "get": {
                    "url": `${apiHost}/rest/1/db/files/json/{_id}?full_object=true`
                },
                "delete": {
                    "url": `${apiHost}/rest/1/db/files/{_id}`
                },
                "find": {
                    "url": `${apiHost}/rest/1/db/files`
                },
              // "update" - not used for files but could be set for other models
            }
        }
    ]
};
export {
    AppClientMetadata
};

Helper properties and methods

state

state: string;

Current AppClient state. Could be one of: initial, offline, online, not_synced, synchronizing, sync_failed

Example

console.log(this.$a.aex.state);

getState

getState(): Promise<{state: string}>

Get current AppClient state.

Returns

Promise with current AppClient state. For example: {state: "offline"}

Example

let state = await this.$a.aex.getState();

getInstance

getInstance(): Promise

Get full mssdk AppClient instance.

Returns

Promise with mssdk AppClient instance.

Example

let mssdk = await this.$a.aex.getInstance();

get

get(entity: string, id, options ? ): Promise

Get item from entity by id.

Parameters

  • entity - name of the collection or model;
  • id - item id;
  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error;
    • cached - get from cache (if true) or make a request to the server (if false). If not specified then try to get data from cache and if nothing was found then make a request to the server.

Returns

Promise with received object

Example

let item = await this.$a.aex.get("tasks", "52c6bfa7e4b03c65ed01f039");

query

query(entity: string, params?: {where?: any; sortBy?: string; limit?: number;}, options?): Promise<any[]>

Query entity.

Parameters

  • entity - name of the collection or model;
  • params - query params object. Seee details. Available params are:
    • where - (optional). object;
    • sortBy - (optional). string;
    • limit - (optional). number;
  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error;
    • cached - get from cache (if true) or make a request to the server (if false). If not specified then try to get data from cache and if nothing was found then make a request to the server.

Returns

Promise with array of received objects

Example

let items = await this.$a.aex.query("tasks", {where: {"status": "done"}});

queryOne

queryOne(entity: string, params?: {where?: any; sortBy?: string;}, options?): Promise

Query entity.

Parameters

  • entity - name of the collection or model;
  • params - query params object. Seee details. Available params are:
    • where - (optional). object;
    • sortBy - (optional). string;
  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error;
    • cached - get from cache (if true) or make a request to the server (if false). If not specified then try to get data from cache and if nothing was found then make a request to the server.

Returns

Promise with received object

Example

let items = await this.$a.aex.queryOne("tasks", {where: {"status": "done"}});

count

count(entity: string, params?: {where?: any}, options ? ): Promise<{count: number}>

Query entity and return count of found objects.

Parameters

  • entity - name of the collection or model;
  • params - query params object. Seee details. Available params are:
    • where - (optional). object;
  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error;
    • cached - get from cache (if true) or make a request to the server (if false). If not specified then try to get data from cache and if nothing was found then make a request to the server.

Returns

Promise with count of found objects. For example: {count: 5}

Example

let count = await this.$a.aex.count("tasks", {where: {"status": "done"}});

save

save(entity: string, obj, options?): Promise

Create or update item. If obj has _id parameter then item will be updated. Otherwise new item will be created.

Parameters

  • entity - name of the collection or model;
  • obj - item to be saved;
  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

Full data of created/saved object. undefined in case of error.

Example

let newItem = {name: "Buy milk", description: "Buy one bottle", status: "new"};
let item = this.$a.aex.save("tasks", newItem);

delete

delete(entity: string, item, options?): Promise

Delete item.

Parameters

  • entity - name of the collection or model;
  • item - item to be deleted (actually only _id property in the item object is needed) or item's _id;
  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

{ "status": "success"} or undefined in case of error.

Example

let res = this.$a.aex.delete("tasks", "65a676d33c62ea0123456789");

clear

clear(entity: string, options?): Promise

Clear cache for the specified entity.

Parameters

  • entity - name of the collection or model;
  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

{ "status": "success"} or undefined in case of error.

Example

let res = this.$a.aex.clear("tasks");

fetch

fetch(entity: string, options?): Promise

Fetch the entity to cache.

Parameters

  • entity - name of the collection or model;
  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

{ "status": "success"} or undefined in case of error.

Example

let res = this.$a.aex.fetch("tasks");

fetchMulty

fetchMulty(entities: string[], options?): Promise

Fetch multiple entities to cache.

Parameters

  • entities - array of names of collections or models;
  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

{ "status": "success"} or undefined in case of error.

Example

let res = this.$a.aex.fetchMulty(["tasks", "dreams"]);

isLoggedIn

isLoggedIn(): Promise

Check if user is logged in.

Returns

true if user is logged in otherwise returns false.

Example

let loggedIn = this.$a.aex.isLoggedIn();

login

login(payload: {username: string, password: string} , options?): Promise

Login with provided credentials.

Parameters

  • payload - user's credentials:
    • username - login;
    • password - password;
  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

Promise with user's data (_id, sessionToken). If login succeed then sessionToken will be automatically set to AppClient and credentials will be saved to storage for autoLogin.

Example

await this.$a.aex.login(
   {
     username: "Joe",
     password: "123"
   }
);

loginAnonymously

loginAnonymously(options?): Promise

Create temporary user and login with this user's credentials.

Login with provided credentials.

Parameters

  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

Promise with user's data (_id, sessionToken). If login succeed then sessionToken will be automatically set to AppClient and credentials will be saved to storage for autoLogin.

Example

await this.$a.aex.loginAnonymously();

logout

logout(options?): Promise

Logout user.

Parameters

  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

Promise with {status: 'success'}

Example

await this.$a.aex.logout();

userCreate

userCreate(data: {username: string, password: string}, options?): Promise

Update current user's data.

Parameters

  • userData - object with user's data (username and password) to be created.

  • options - (optional). Available options are:

    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

Promise with user's data (_id, sessionToken, username).

Example

await this.$a.aex.userCreate({  
  username: "[email protected]",
  password: "12345"
});

userGetData

userGetData(options?): Promise

Get current user's data.

Parameters

  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

Promise with the user's data (_id, username).

Example

let userData = await this.$a.aex.userGetData();

userUpdate

userUpdate(data: {username: string, password: string}, options?): Promise

Update current user's data.

Parameters

  • userData - object with user's data (username and password) to be updated.
  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

Promise with the full user's data.

Example

await this.$a.aex.userUpdate({  
  username: "[email protected]",
  password: "12345"
});

userRemove

userRemove(options?): Promise

Remove current user.

Parameters

  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

Promise with {status: 'success'}

Example

await this.$a.aex.userRemove();

getSessionToken

getSessionToken(): Promise<string|undefined>

Get current Session Token.

Returns

Current Session Token or undefined if Session Token was not set.

Example

let token = await this.$a.aex.getSessionToken();

setSessionToken

setSessionToken(data: {token: string}, options?): void

Set session token. If you login with login or userCreate then session token will be set automatically and there is no need to set session token with this method.

Example

await this.$a.aex.setSessionToken({token:"86a3f366-ec22-4006-9571-05b49965aef2"});

clearUserData

clearUserData(options?): Promise

Clear all deferred actions and cache.

Parameters

  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

Promise.

Example

await this.$a.aex.clearUserData();

addListener

addListener(event: string, listener: Function): Promise

Add listener for the specified AppClient event.

Parameters

  • event - name of the event. Available events are: statechange, init, auth.success, auth.failed, auth.logout
  • listener - function to be invoked when specified event fires

Returns

Promise with undefined

Example

const func = (newState) => console.log(newState);
await this.$a.aex.addListener("statechange", func);

removeListener

removeListener(event: string, listener: Function): Promise

Remove listener for the specified AppClient event.

Parameters

  • event - name of the event. Available events are: statechange, init, auth.success, auth.failed, auth.logout
  • listener - function

Returns

Promise with undefined

Example

const func = (newState) => console.log(newState);
await this.$a.aex.addListener("statechange", func);
.........................
await this.$a.aex.removeListener("statechange", func);

goOnline

goOnline(options?): Promise

Set current state to online after goOffline.

Parameters

  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

Promise.

Example

await this.$a.aex.goOnline();

goOffline

goOnline(options?): Promise

Emulate offline state.

Parameters

  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

Promise.

Example

await this.$a.aex.goOffline();

retrySync

retrySync(options?): Promise<{status: string}>

Retry synchronization. Call it before getConflict to get full data from server (see httpErrorResponse property).

Parameters

  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

Promise with {status: 'failed'} or {status: 'success'}.

Example

await this.$a.aex.retrySync();

getConflict

getConflict(options?): Promise

Get next conflict.

Parameters

  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

Promise with object.

{
	status: "success"|undefined, // if "success" then no conflict was found
  content: {
  	data: {....}, // new data (after editing)
    revertedData: {....} // data before editing
  },
  httpErrorResponse: {
  	httpStatus: number,
    modifiedEntityNode: {....}, // current item data from server
    response: {....}, // server response
    responseHeaders: {....},// server response headers
    statusText: string
  },
  modelName: string, // Name of the current model
  operation: string // Current operation ("UPDATE", "CREATE", etc.)
}

Example

let conflict = await this.$a.aex.getConflict();

resolveConflict

resolveConflict(data?: {action?: string, data?: any}, options?): Promise

Get next conflict.

Parameters

  • data - (optional):
    • action - string. One of "UPDATE", "UNDO", "DELETE"
    • data - new data (in case of UPDATE action). In case of UPDATE action set _updatedAt property of the new data to the current value from server (conflict.httpErrorResponse.modifiedEntityNode._updatedAt)
  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Returns

Promise with {status: 'failed'} or {status: 'success'}.

Example

await this.$a.aex.retrySync();
let conflict = await this.$a.aex.getConflict();
let newData = conflict.content.data;
newData._updatedAt = conflict.httpErrorResponse?.modifiedEntityNode?._updatedAt;
await this.$a.aex.resolveConflict({action: "UPDATE", data: newData}, {loading: true});

resetFailedSync

resetFailedSync(options?): Promise

Reset all deferred actions.

Parameters

  • options - (optional). Available options are:
    • loadingStart - show loading on service execution start (default is false);
    • loadingEnd - hide loading on service execution end (default is false);
    • loading - boolean. Shortening for (loadingStart = true and loadingEnd = true);
    • showError - show toast with error if error occurs (default is true);
    • message - message to be shown after success service execution;
    • errorMessage - message to be shown after error in service execution;
    • throwError - throw error if service execution ends with error.

Example

await this.$a.aex.resetFailedSync()