RhoConnectClient is used for synchronization with RhoConnect applications.
In order to use this API you must include the following extension in your build.yml
extensions: ["rhoconnect-client"]
Be sure to review the JavaScript API Usage guide for important information about using this API in JavaScript
Be sure to review the Ruby API Usage guide for important information about using this API in Ruby
Add the object notification by passing in an object ID.
Parameters
Source name for object notification.
Object ID to get notifications.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.addObjectNotify(STRING sourceName, STRING object)
Rho::RhoConnectClient.addObjectNotify(STRING sourceName, STRING object)
Removes callback for object notifications.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.cleanObjectNotify()
Rho::RhoConnectClient.cleanObjectNotify()
Clears the sync notification for a given source.
Parameters
Source name to clear notification. Use ‘*’ to clear notification for all models.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.clearNotification(STRING sourceName)
Rho::RhoConnectClient.clearNotification(STRING sourceName)
Start the RhoConnectClient sync process.
Parameters
Set to true to show status popup.
Parameters to be passed to server.
The value must be like 'query=<your params here> . Your params may be just a string or string representation of JSON structure. For example: 'query=abc' or 'query={abc: "foo"}'
Sync only sources that have local changes.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.doSync(BOOLEAN showStatusPopup, STRING queryParams, BOOLEAN syncOnlyChangedSources)
Rho::RhoConnectClient.doSync(BOOLEAN showStatusPopup, STRING queryParams, BOOLEAN syncOnlyChangedSources)
Start RhoConnectClient sync process for a given source name.
Parameters
Source name.
Set to true to show status popup.
Parameters to be passed to server.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.doSyncSource(STRING sourceName, BOOLEAN showStatusPopup, STRING queryParams)
Rho::RhoConnectClient.doSyncSource(STRING sourceName, BOOLEAN showStatusPopup, STRING queryParams)
Returns true if the RhoConnectClient currently has a user session, false if not.
Synchronous Return:
True if have logged in user session, false if not.
Method Access:
Rho.RhoConnectClient.isLoggedIn()
Rho::RhoConnectClient.isLoggedIn()
Returns true if sync is currently in progress.
Synchronous Return:
True if sync has started but not finished yet, false otherwise.
Method Access:
Rho.RhoConnectClient.isSyncing()
Rho::RhoConnectClient.isSyncing()
Authenticates the user with RhoConnect. The callback will be executed when it is finished.
Parameters
Login name.
Password.
Async Callback Returning Parameters: INTEGER
Synchronous Return:
Method Access:
Rho.RhoConnectClient.login(STRING login, STRING password, CallBackHandler callback)
Rho::RhoConnectClient.login(STRING login, STRING password, CallBackHandler callback)
Logout the user from the RhoConnect server. This removes the local user session.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.logout()
Rho::RhoConnectClient.logout()
If you have a large dataset in your backend service, you don’t have to synchronize everything with the RhoConnectClient. Instead you can filter the synchronized dataset using the RhoConnectClient’s search function. Provide callback, which will be executed after search is completed.
(Not currently supported in JavaScript.)
Parameters
Hash of arguments passed to search.
Array of source names to be included in search result.
Default is ‘search’
Hash of key-value pairs to be included in search result.
Maximum number of results to be returned.
If true and there are local changes, client sync will be triggered before search.
Async Callback Returning Parameters: OBJECT
Resulting status of search. ‘ok’ of completed successfully, ‘error’ otherwise.
Search_params originally provided for the search call. Typically you want to forward the original search_params to your view that displays the results so you can perform the same query locally. Please see examples section.
Synchronous Return:
Will return value only if threadedMode set to false. Otherwise search results returned in callback.
: this method also supports async callbacks - check the Callback tab for callback return parameters.Method Access:
Rho::RhoConnectClient.search(HASH args, CallBackHandler callback)
The RhoConnectClient system uses notifications to provide information about the sync process to a Rhodes application. Notifications can be setup once for the duration of runtime or each time a sync is triggered. Once a sync is processing for a model, notifications are called with parameters containing sync process state. Your application can use this information to display different wait pages, progress bars, etc. setNotification will set notification for a model.
Parameters
Source name for which notification will be enabled. Use ‘*’ to set notification for all models.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.setNotification(STRING sourceName, CallBackHandler callback)
Rho::RhoConnectClient.setNotification(STRING sourceName, CallBackHandler callback)
The RhoConnectClient can send a notification when a specific object on the current page has been modified. This is useful if you have frequently-changing data like feeds or timelines in your application and want them to update without the user taking any action.
Parameters
Async Callback Returning Parameters: OBJECT
Array of created objects.
Array of updated objects.
Array of deleted objects.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.setObjectNotification(CallBackHandler callback)
Rho::RhoConnectClient.setObjectNotification(CallBackHandler callback)
Stops any sync operations currently in progress.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.stopSync()
Rho::RhoConnectClient.stopSync()
Set 0 to force bulk sync on next synchronization cycle. After sync is complete, bulksyncState will be set to 1.
(Not currently supported in JavaScript.)
Default: 1
Property Access:
myObject.bulksyncState
Page size for RhoConnectClient. Default size is 2000.
Property Access:
myObject.pageSize
Sync poll interval in seconds. Setting this to 0 will disable polling-based sync. Sync process will be triggered automatically according to this setting.
Default: 60
Property Access:
myObject.pollInterval
Enable or disable show status popup.
Default: true
Property Access:
myObject.showStatusPopup
Enable or disable verification of RhoConnect ssl certificates, true by default.
Default: true
Property Access:
myObject.sslVerifyPeer
Sync server URL.
Property Access:
myObject.syncServer
Current username of the RhoConnectClient session if isLoggedIn is true, otherwise returns the last logged in username.
Property Access:
myObject.userName
In your controller call login.
Rho.RhoConnectClient.login('john','password',function(result){ loginCallback(result); });
RhoConnectClient.login( @params['login'], @params['password'], url_for(:action => :login_callback) )
When RhoConnectClient.login completes, the callback declared is executed and receives parameters including success or failure and error messages (if any).
// Error codes: // ERR_NONE = 0 // ERR_NETWORK = 1 // ERR_REMOTESERVER = 2 // ERR_RUNTIME = 3 // ERR_UNEXPECTEDSERVERRESPONSE = 4 // ERR_DIFFDOMAINSINSYNCSRC = 5 // ERR_NOSERVERRESPONSE = 6 // ERR_CLIENTISNOTLOGGEDIN = 7 // ERR_CUSTOMSYNCSERVER = 8 // ERR_UNATHORIZED = 9 function loginCallback(result) { var errorCode = parseInt(result.error_code); var errorMessage = result.error_message; if(errorCode === 0 { // process success } else { // process error with errorMessage } }
# Error codes: # ERR_NONE = 0 # ERR_NETWORK = 1 # ERR_REMOTESERVER = 2 # ERR_RUNTIME = 3 # ERR_UNEXPECTEDSERVERRESPONSE = 4 # ERR_DIFFDOMAINSINSYNCSRC = 5 # ERR_NOSERVERRESPONSE = 6 # ERR_CLIENTISNOTLOGGEDIN = 7 # ERR_CUSTOMSYNCSERVER = 8 # ERR_UNATHORIZED = 9 def login_callback error_code = @params['error_code'].to_i if error_code == Rho::RhoError::ERR_NONE # run sync if we were successful WebView.navigate Rho::RhoConfig.options_path RhoConnectClient.doSync else if error_code == Rho::RhoError::ERR_CUSTOMSYNCSERVER @msg = @params['error_message'] end if not @msg or @msg.length == 0 @msg = Rho::RhoError.new(error_code).message end WebView.navigate( url_for(:action => :login, :query => {:msg => @msg}) ) end end
First, assign a sync notification for the Account model:
function syncNotify(params) { // handle notifications... } Rho.RhoConnectClient.setNotification('Account', syncNotify);
RhoConnectClient.setNotification( 'Account', url_for(:action => :sync_notify), "sync_complete=true" )
Which is the same as:
function syncNotify() { // handle notifications... } Account.setNotification(syncNotify);
Account.setNotification( url_for(:action => :sync_notify), "sync_complete=true" )
You can also set a notification for all models:
function syncNotify(params) { // handle notifications... } Rho.RhoConnectClient.setNotification('*', syncNotify);
RhoConnectClient.setNotification( '*', url_for(:action => :sync_notify), "sync_complete=true" )
To use object notifications, first set the notification callback in application.rb#initialize.
class AppApplication < Rho::RhoApplication def initialize super RhoConnectClient.setObjectNotification( url_for( :controller => "Product", :action => :sync_object_notify ) ) end end
Next, in your controller action that displays the object(s), add the object notification by passing in a record or collection of records:
function syncObjectNotified(params) { // handle notifications... } var product = Product.find('first'); Rho.RhoConnectClient.addObjectNotify('Product', product.id);
class ProductController < Rho::RhoController # GET /Product def index @product = Product.find(:first) RhoConnectClient.addObjectNotify('Product', @product.id) render end # ... def sync_object_notified # process notification data ... # refresh the current page WebView.refresh # or call System.execute_js to update part of the page end end
Here we will set a notification and log an error code 1 or ERR_NETWORK:
function syncNotify(result) { var errorCode = parseInt(result.error_code); var errorMessage = result.error_message; if(errorCode === 1) { console.log("We received a network error: " + errorMessage); return; } } Rho.RhoConnectClient.setNotification('*', syncNotify);
RhoConnectClient.setNotification( '*', url_for(:action => :sync_notify), "sync_complete=true" ) # In your controller: def sync_notify error_code = @params['error_code'].to_i error_message = @params['error_message'] if error_code == Rho::RhoError::ERR_NETWORK puts "We received a network error: " + error_message end end
First, call search from your controller action:
def search page = @params['page'] || 0 page_size = @params['page_size'] || 10 RhoConnectClient.search( { 'Contact', :from => 'search', :search_params => { :FirstName => @params['FirstName'], :LastName => @params['LastName'], :Company => @params['Company'] }, :offset => page * page_size, :max_results => page_size } url_for(:action => :search_callback) ) render :action => :search_wait end
The search_params
will be forwarded to your callback so you can update the view with the results:
def search_callback status = @params["status"] if (status and status == "ok") WebView.navigate( url_for( :action => :show_page, :query => @params['search_params'] ) ) else render :action => :search_error end end def show_page @contacts = Contact.find( :all, :conditions => { { :func => 'LOWER', :name => 'FirstName', :op => 'LIKE' } => @params[:FirstName], { :func => 'LOWER', :name=>'LastName', :op=>'LIKE' } => @params[:LastName], { :func=>'LOWER', :name=>'Company', :op=>'LIKE' } => @params[:Company], }, :op => 'OR', :select => ['FirstName','LastName', 'Company'], :per_page => page_size, :offset => page * page_size ) render :action => :show_page end
When the notification is called, it will receive a variable called @params, just like a normal Rhodes controller action.
These parameters are included in all notifications.
In the following sections we cover the different status values and parameters available with each status.
bulk_status – The state of the bulk sync process:
partition – Current bulk sync partition.
Each error contains a ‘message’ key with the error message.
Ruby Example:
@params["server_errors"]["query-error"]["message"] #=> "Error connecting to backend server: http://rhostore.herokuapp.com"
JavaScript Example:
params.server_errors["query-error"].message //=> "Error connecting to backend server: http://rhostore.herokuapp.com"
“create-error” is a unique situation that needs to be handled in your sync callback. See RhoConnectClient.onSyncCreateError()
for more details.
This status returns only when the sync run is complete (all partitions are done synchronizing).
This is present if a FixedSchema model has changed during the current sync run. A new bulk sync run should be triggered (by setting bulksyncState) and the user should be alerted in the UI.
On iOS, if the application is backgrounded, it will be suspended. This also means if a current sync is in progress, it will immediately terminate. To prevent this behavior, set ‘finish_sync_in_background’ to ‘1’ in rhoconfig.txt. When set to ‘1’, the RhoConnectClient will attempt to finish synchronization before the application fully suspends.