WebSyncTable : Web SyncTable server

更新时间:
2024-05-15
下载文档

WebSyncTable : Web SyncTable server

The WebSyncTable module is a server for multitasking SyncTable objects. This service uses WebSocket to communicate with the Web. The Web environment can set and get the contents of SyncTable objects.

User can use the following code to import the WebSyncTable module.

var WebSyncTable = require('websynctable');

Support

The following shows WebSyncTable module APIs available for each permissions.

 User ModePrivilege Mode
WebSyncTable
server.close
server.reverse
server.clients

WebSyncTable Class

new WebSyncTable(server, table[, opt])

  • server {Object | HttpServer | WebApp} Network server.
  • table {SyncTable} SyncTable object.
  • opt {Object} Optional parameters.
    • alive {Integer} The longest time the client is unresponsive. default: 5000ms.
    • filter {Function} When the client set or get the key, this function can be provided for permission check, and the set or get is allowed to return true, otherwise returns false. default: true.
      • client {Object} Client.
      • set {Boolean} Set is true, get is false.
      • key {Number | String} The key set by the client.
      • value {Number | String | Buffer | Object} The value set by the client. only set have this argument.
    • onclient {Function} Client connection and disconnection event callback.
      • event {String} 'connect' or 'disconnect'.
      • client {Object} Client.
  • Returns: {WebSyncTable} WebSyncTable server object.

Create a SyncTable server, the server parameter can refer to the WebSocket server documentation.

The filter function argument client object includes following members:

  • url {String} Request url.
  • eos {Object} EdgerOS account and connection information. See eos middleware for details.
  • channel {WsServerChannel} WebSocketChannel object.
  • close {Function} Close this client. The client can add many SyncTables to a websocket connection, calling this function will close the websocket connection with this client.

Example

var WebApp = require('webapp');
var SyncTable = require('synctable');

var app = WebApp.createApp(/* ... */);
var table = new SyncTable('table1');

// Create SyncTable server
var server = new WebSyncTable(app, table);
  • Create server with filter
// Create SyncTable server with filter
var server = new WebSyncTable(app, table, {
  filter: function(client, set, key, value) {
    // Client can not get and set key: foo value
    return key !== 'foo';
  }
});

onclient function is used to get the client connection information.

Example

// Create SyncTable server with onclient
var server = new WebSyncTable(app, table, {
  onclient: function(event, client) {
    if (event === 'connect') {
      console.log('New client connect!');
    } else {
      console.log('Client lost!');
    }
  }
});

The client object contains the query object, which is the query object of the WebSocket request URL. This query can be used for identity authentication in non-EdgerOS environments (the front end needs to add token and srand). In EdgerOS environments, you only need to obtain the client.eos object to obtain the parsed ACOID information.

Example

var t1 = new SyncTable('t1');
var t2 = new SyncTable('t2');

var s1 = new WebSyncTable(app, t1);
var s2 = new WebSyncTable(app, t2);

WebSyncTable Object

server.close()

Close this WebSyncTable server, all client requests will no longer respond.

server.reverse(event, arg[, client])

  • event {String} Event message name.
  • arg {Number | String | Object} Event message argument.
  • client {Object} Target client. default: broadcast to all clients.
  • Returns: {Boolean} Whether the transmission was successful.

Send a custom message to the specified client or broadcast to all clients.

If the return value is false, it means that this client has been disconnected, please do not try to send information to this target again.

Example

server.reverse('my_notify', { foo: 'bar' });

server.clients()

  • Returns: {Integer} Number of client connections.

Get the number of client connections.

Events

WebSyncTable inherits from the EventEmitter class. When the client fetch() commands, WebSyncTable object will generate such events.

The event parameters generated are as follows:

  • arg {Any} Client fetch argument.
  • client {Object} Client.
  • reply {Function} Reply to client.
    • arg {Any} Reply to client argument.

Example

server.on('my_command', function(arg, client, reply) {
  reply({ res: 'ok', msg: 'my_command ok!' });
});

Front-End

The front end can use the following code to realize the docking with the WebSyncTable server:

<script src="synctable.min.js"></script>

Support

The following shows SyncTable client module APIs.

API 
SyncTable
table.close
table.name
table.has
table.set
table.get
table.delete
table.fetch
table.onmessage
table.addEventListener
table.removeEventListener

SyncTable Class

new SyncTable(server, name[, opt])

  • server {String} WebSocket URL.
  • name {String} Server SyncTable name.
  • opt {Object} Optional parameters.
    • ping {Integer} Period of sending ping information, default 3000ms.
    • timeout {Integer} Asynchronous operation timeout. default: 6000ms.
    • token {String} EdgerOS account token, which can be obtained by EdgerOS Web-SDK.
    • srand {String} EdgerOS login serial number, which can be obtained by EdgerOS Web-SDK.
  • Returns: {SyncTable} SyncTable client object.

Create an SyncTable client in the Front-End.

Example

var table = new SyncTable('ws://xxxx.com', 'table1');

Example

// You must import @edgeros/web-sdk module
var opt = {};
var table = null;
var proto = location.protocol === 'http:' ? 'ws:' : 'wss:';
var server = `${proto}//${window.location.host}`;

// First get token and srand
edger.token().then(data => {
  opt.token = data.token;
  opt.srand = data.srand;
}).catch(error => {
  console.warn('Not in EdgerOS!');
});

// EdgerOS Update token and srand
edger.onAction('token', data => {
  opt.token = data.token;
  opt.srand = data.srand;
});

// Create SyncTable
table = new SyncTable(server, 'table1', opt);

table.close()

Close the current object, this object is not allowed to be accessed after this function is called.

table.name

  • {String}

SyncTable name when creating this object.

table.has(key)

  • key {Number | String} Table key.
  • Returns: {Promise} Promise object.

Get whether the value of the specified key exists in SyncTable.

Example

table.has('k1').then(has => {
  console.log('has k1:', has); 
}).catch(e => {
  console.error('has error!');
});

table.set(key, value)

  • key {Number | String} Table key.
  • value {Number | String | Uint8Array | Object} This key's value.
  • Returns: {Promise} Promise object.

Set the value of a specified key. This method is asynchronous. The timeout time is opt when the SyncTable is created opt.timeout specified time.

Example

table.set('k1', 'v1').then(v => {
  console.log('ok'); 
}).catch(e => {
  console.error('set error!');
});

// use async function
async function setValue() {
  try {
    var value = await table.set('k1', 'v1');
  } catch (error) {
    console.error('Error:', error.message);
    return;
  }
  console.log('k1 value is:', value);
}

table.get(key)

  • key {Number | String} Table key.
  • Returns: {Promise} Promise object.

Get the value of the specified key. There are some key values cached in the SyncTable object. When the cache is valid, the Promise object will immediately be converted to the fulfilled state. When it is invalid, SyncTable will request the server to obtain this data. The timeout time is opt when the SyncTable is created opt.timeout specified time.

Example

table.get('k1').then(value => {
  console.log('k1 value is:', value);
}).catch(error => {
  console.error('get k1 value error!');
});

// use async function
async function getValue() {
  try {
    var value = await table.get('k1');
  } catch (error) {
    console.error('Error:', error.message);
    return;
  }
  console.log('k1 value is:', value);
}

table.delete(key)

  • key {Number | String} Table key.
  • Returns: {Promise} Promise object.

Equivalent to table.set(key, undefined).

table.fetch(command[, arg[, delay[, delta]]])

  • event {String} Command.
  • arg {Number | String | Object} Event argment.
  • delay {Boolean} Whether to delay sending. default: false.
  • delta {Number} Timeout offset. default: 0.
  • Returns: {Promise} Promise object.

Send a command to the server and asynchronously wait for the server to reply. If delay is false, the command will NOT be sent when there is no connection with the server, and the Promise object will immediately become rejected. If the delay is true, if the server is reconnected within the timeout period, SyncTable will send this command to the server.

The default timeout time of the fetch() is the time specified by opt when creating the SyncTable. If the server needs to execute this command for a long time, you can set delta to adjust the timeout time. For example, if opt.timeout is 6000, delta is 1000, the fetch() timeout time is 7000ms , If delta is -1000, the timeout time is 5000ms, this function is supported in SyncTable 0.1.6 and later.

Example

table.fetch('my_command', { foo: 'bar' }).then(ret => {
  console.log('server reply:', ret);
}).catch(error => {
  console.error('my_command error:', error.message);
});

table.onmessage(event, arg)

  • event {Number | String} Message event.
  • arg {Number | String | Uint8Array | Object} Event argment.

Users can set this function to get asynchronous messages pushed by the server (WebSyncTable object reverse() method call):

Example

table.onmessage = function(event, arg) {
  console.log(`Receive message ${event} with argument ${arg} from server!`);
}

table.addEventListener(event, listener)

  • event {String} SyncTable object event to listen.
  • listener {Function} This event listener.

The SyncTable object will generate the following events when working:

Event nameDescriptionArgument
'connect'Connected to the specified server.
'disconnect'The connection to the server was disconnected.
'clear'SyncTable is cleared
'update'Value is updatedkey, value
'error'There is an errorerror (Error object)

Example

table.addEventListener('connect', function() {
  console.log('connected!');
});

table.addEventListener('disconnect', function() {
  console.log('disconnected!');
});

table.addEventListener('clear', function() {
  console.log('clear!');
});

table.addEventListener('update', function(key, value) {
  console.log('update!', key, value);
});

table.addEventListener('error', function(error) {
  console.error('error:', error);
});

table.removeEventListener(event, listener)

  • event {String} SyncTable object event.
  • listener {Function} This event listener need to be removed.

Delete the listener added before.

文档内容是否对您有所帮助?
有帮助
没帮助