Skip to content
Pablo Ojanguren edited this page Mar 20, 2017 · 1 revision

JavaScript API

Text Editor Component

Depecrated API methods

These methods are deprecated and they will be removed from the JS client eventually.

JavaScript API

createUser

SwellRT.createUser(parameters, onComplete)

Create a new user account.

SwellRT.createUser(

    // Parameters

    {
        id: "elvis",// (Required) the user id
        password: "_password_", // (Optional)
        email: "[email protected]", // (Optional) an email address
        locale: "en_GB",             // (Optional) the locale
        avatarData: "data:image/png;base64,iVBORw0K (...)", // (Optional) a Base64 image
    },

    // onComplete callback

    function(res) {

        if (res.error) {

            if (res.error == "ACCOUNT_ALREADY_EXISTS") {

            }

            console.log(error);

        } else if (res.data) {

           // data.avatarUrl = (relative path) '/swell/account/elvis/avatar/<filename>.png'
           // data.email
        }

    });

Error Codes: "ACCOUNT_ALREADY_EXISTS", "ACCOUNT_ID_WRONG_SYNTAX","INVALID_EMAIL_ADDRESS"

updateUserProfile

SwellRT.updateUserProfile(parameters, onComplete)

Update the profile data of the current logged in user. To change the user's password see the setPassword(...) function.

SwellRT.updateUserProfile(

    // Parameters

    {
        email: "[email protected]", // (Optional) an email address
        locale: "en_GB",             // (Optional) the locale
        avatarData: "data:image/png;base64,iVBORw0K (...)", // (Optional) a Base64 image
    },

    // onComplete callback

    function(res) {

        if (res.error) {

            console.log(error);

        } else if (res.data) {

           // data.avatarUrl = (absolute path) 'http://api.swellrt.org/swell/account/elvis/avatar/<filename>.png'
           // data.email
        }

    });

To delete any value, update with empty value, e.g. avatarData : "".

Error Codes: "INVALID_EMAIL_ADDRESS"

getUserProfile

SwellRT.getUserProfile(onComplete)

Gets the profile data from the current logged in use.

SwellRT.getUserProfile(

    // onComplete callback

    function(res) {

        if (res.error) {

            console.log(error);

        } else if (res.data) {

           // data.avatarUrl
           // data.email
           // data.locale

        }

    });

SwellRT.getUserProfile(array of users,onComplete)

Gets the profile data of a list of provided users

SwellRT.getUserProfile(


    ['[email protected]', '[email protected]', ... ],

    // onComplete callback

    function(res) {

        if (res.error) {

            console.log(error);

        } else if (res.data) {

           // data = array of profile data

        }

    });

login

SwellRT.login(parameters, onComplete)

Start a session with an user and password credentials. On success, returns the user's profile data and the session token.

SwellRT.login(

    // Parameters

    {
        id : "[email protected]",
        password : "the-password"
    },


    // onComplete callback

    function(res) {

        if (res.error) {

            console.log(error);

        } else if (res.data) {

           // data.sessionId (the session token)
           // data.email
           // data.locale

        }

    });

Error Codes: "LOGIN_FAILED", "INVALID_ACCOUNT_ID_SYNTAX", "MISSING_PARAMETER"

resume

SwellRT.resume(onComplete)

Resume the last opened session in the browser if it is alive active in the server. On success, returns the user's profile data and the session token.

SwellRT.resume(

    // onComplete callback

    function(res) {

        if (res.error) {

            console.log(error);

        } else if (res.data) {

           // data.sessionId (the session token)
           // data.email
           // data.locale

        }

    });

Resume an existing session in the browser if it is still alive in the server. On success, returns the user's profile data and the session token.

SwellRT.resume(

    {
        id : "[email protected]"
    },


    function(res) {

        if (res.error) {

            console.log(error);

        } else if (res.data) {

           // data.sessionId (the session token)
           // data.email
           // data.locale

        }

    });

logout

SwellRT.logout(onComplete)

Closes the user session with the server and cleans up all the associated connections and data. It also cleans up all editors.

SwellRT.logout(


    // onComplete callback

    function(res) {

        if (res.error) {

            console.log(error);

        } else if (res.data.status == "SESSION_CLOSED") {

           // the server has closed the session
        }

    });

This method can be used to log out a specific user session also destroying it in the server.

SwellRT.logout(

    {
        id : "[email protected]"
    },

    function(res) {

        if (res.error) {

            console.log(error);

        } else if (res.data.status == "SESSION_CLOSED") {

           // the server has closed the session
        }

    });

open

SwellRT.open(options,onComplete)

Opens or create a collaborative object. For the options object, set the "id" field to open an existing object. Otherwise a object will be created.

This function opens a Websocket channel with the server.

SwellRT.open(
    {
      // Don't set id to create a new object
      id : "local.net/s+nFGvgdYeJbA"
    },
    function(co) {

      if (co == null) {
        // Error
      } else if (co.error)  {
        // Error
      }

      // Success

      });

close

SwellRT.close(objectRef)

Closes the collaborative object releasing connection with server and local resources. Clean up editors showing any object text field.

objectRef can be set with:

  • the collaborative object
  • the collaborative object's id
  • any object with an "id" field

This method doesn't require asynchronous callback.

SwellRT.close(
    {
      id : "local.net/s+nFGvgdYeJbA"
    })

query

SwellRT.query(expresion, onSuccess, onFailure)

Query the server for collaborative objects. Only objects that can be accessed by the current logged in user will be returned. This methods query the underlying mongoDB static store of objects. Returned JS objects are not "live" objects.

SwellRT.query(

    {
 
        _query : { ... },   // query object

        _projection: { ... }, // projection object

        _aggregate: [ ... ] // // aggregation expressions

    }, 

    function (response)  {

    },

    function (error)  {

    }

);

The response object has the following syntax:

{
    "result":[  // array of objects

         { 
               // first object's JSON 
         },

         { 
               // second object's JSON 
          }
    ]
}

Exceptions: SESSION_NOT_STARTED_EXCEPTION, REQUEST_EXCEPTION

recoverPassword

SwellRT.recoverPassword(userEmail, recoverUrl, onSuccess, onFailure)

Send an email to the user with email userEmail with a custom link created from recoverUrl to reestablish her password.

Parameter Description
userEmail Email address of the user that wants to recover her password. It sould be registered in her profile.
recoverUrl the URL to reestablish the password. It should have the following syntax: *$token*$user-id*. Server will replace $token and $user-id by actual token and user-id before sharing it with userEmail
onSuccess function(result:Object) callback function receiving the JSON result object.
onFailure function(e:String)callback function receiving the error code: SERVICE_EXCEPTION

setPassword

SwellRT.setPassword(user, token, newPassword, onSuccess, onFailure)

SwellRT.setPassword(user, oldPassword, newPassword, onSuccess, onFailure)

Changes the password if the user knows previous password or has a recovery token from recoverPassword method.

Parameter Description
user User name with syntax name[@domain]. If domain is not specified, the server's SwellRT domain will be used.
token Recovery token obtaineed by SwellRT.recoverPassword method
oldPassword Users current password to authorize the password change
onSuccess function(result:Object) callback function receiving the JSON result object.
onFailure function(e:String)callback function receiving the error code: SERVICE_EXCEPTION

Text Editor Component

Create / Update annotations

  • setAnnotation(String key, String value):Annotation
  • setAnnotationInRange(Range range, String key, String value):Annotation

Query annotations

  • getAnnotationSet():Array<Annotation>
  • getAnnotationInRange():Annotation

Query selection or caret

  • getSelection():Range

Remove annotations

  • clearAnnotation(String prefixOrKey)
  • clearAnnotationsInRange(Range range, prefixOrKey)

Text operations

  • setText(Range range, String text):Range
  • getText(Range range): String
  • deleteText(rRange range): void

Annotation Controller object

"<annotation key>" : {

    styleClass: <String>,
    style: <Object>,
    onEvent: function(range, event) { ... },
    onChange: function(range) { ... }

}

Annotation Types

  • style/* (not support for controllers)
  • paragraph/* (not support for controllers)
  • paragraph/header
  • link
  • Custom annotations, require to register custom controllers

Depecrated API methods

SwellRT.startSession

Syntax: SwellRT.startSession(serverUrl, user, password, onSuccess, onFailure)

Starts a new session in the server and opens the communication channel. Anonymous sessions can be started using as user the constant SwellRT.user.ANONYMOUS and an empty password. Further API operations can be done as soon as the onSuccess callback is invoked.

Parameter Description
serverUrl URL to the server including protocol (http or https) and port. Example: http://demo.swellrt.org.
user User name with syntax name[@domain]. If domain is not specified, the server's SwellRT domain will be used.
password User password.
onSuccess function(session:Object) callback function receiving the session info.
onFailure function(e:String)callback function receiving the error code: ACCESS_FORBIDDEN_EXCEPTION, SERVICE_EXCEPTION

If the request can't be sent to the server a REQUEST_EXCEPTION is thrown.

SwellRT.stopSession

Syntax: SwellRT.stopSession()

Stops the current user session closing the communications channel and disposing all uncommited data. If there is no session already started a SESSION_NOT_STARTED_EXCEPTION is thrown.

SwellRT.resumeSession

Syntax: SwellRT.resumeSession(onSuccess, onFailure)

Resume the user's session and opens the communication channel if the session cookie is available and it is accepted by the server. Further API operations can be done as soon as the onSuccess callback is invoked.

Parameter Description
onSuccess function(session:Object) callback function receiving the session info.
onFailure function(e:String)callback function receiving the error code: ACCESS_FORBIDDEN_EXCEPTION, SERVICE_EXCEPTION

If the request can't be sent to the server a REQUEST_EXCEPTION is thrown.

SwellRT.openModel

Syntax: SwellRT.openModel(dataModelId, onReady)

Open or create a collaborative data model.

Parameter Description
dataModelId Id of a collaborative data model. It it doesn't exist it will be created.
onReady function(dataModel:Object) callback function receiving the collaborative data model object

A INVALID_ID_EXCEPTION is thrown if data model id has a wrong syntax.

A NETWORK_EXCEPTION is thrown if server connection is not available.

A SESSION_NOT_STARTED_EXCEPTION is thrown if no session is already started.

If the operation is refused by the server an exception will be notified as a SwellRT.events.FATAL_EXCEPTION. In this case, clients must discard the collaborative data model.

SwellRT.createModel

Syntax: SwellRT.createModel(onReady)

Create a new collaborative data model.

Parameter Description
onReady function(dataModel:Object) callback function receiving the collaborative data model object

A NETWORK_EXCEPTION is thrown if server connection is not available.

A SESSION_NOT_STARTED_EXCEPTION is thrown if no session is already started.

If the operation is refused by the server an exception will be notified as a SwellRT.events.FATAL_EXCEPTION. In this case, clients must discard the collaborative data model.

SwellRT.closeModel

Syntax: SwellRT.closeModel(dataModelId)

Close a collaborative data model. Any further operation in the collaborative data model won't be notified to the server. Consider to dispose all references to the collaborative data model.

Parameter Description
dataModelId Id of a collaborative data model.

An INVALID_ID_EXCEPTION is thrown if data model id has a wrong syntax, doesn't exist or it is not opened.

A SESSION_NOT_STARTED_EXCEPTION is thrown if no session is already started.