published in 'Kontraktor' on Juptr.io

0
0

The best code is unwritten code

 

R.Möller

Shortest way to remote a Service in JavaScript

Handling and mapping remote calls can be cumbersome, monotonous and error prone. Here's a shortcut ... 

 
 

A by product of kontraktor's java/javascript remote interoperation library is a simple way to expose an ES6 class over WebSockets to other nodejs processes. 

Basically, an ordinary ES6 class is exposed via a WebSocket using a one liner (27):

1
    1 
    2 const ks = require('kontraktor-server');
    3 
    4 class MyService {
    5 
    6   greet( whom ) {
    7     return "Hello "+JSON.stringify(whom,2);
    8   }
    9 
   10   timeService( callback ) {
   11     setTimeout( () => {
   12       if ( ! callback.closed ) {
   13         callback.complete(new Date().getTime(), 'CNT' /*keep callback alive*/ );
   14         this.timeService(callback);
   15       } else {
   16         // client disconnected or some other party closed the callback
   17       }
   18     }, 1000 );
   19   }
   20 
   21   // notification callback
   22   clientClosed(map,id) {
   23     console.log("client closed ",map,id);
   24   }
   25 }
   26 
   27 new ks.KontraktorServer(new MyService(),{port:4999});

The service can greet and it's also possible to subscribe to a stream of time (updated each second).

A client can connect and call stuff like this:

 
    1 const kc = require('kontraktor-client');
    2 
    3 new kc.KClient()
    4   .connect("ws://localhost:4999","WS").then( (service,error) => {
    5     if ( service != null ) {
    6       service.$timeService( (res,err) => {
    7         if ( res != null )
    8           console.log( new Date(res) );
    9       });
   10       service.greet( { json:[ 1,2,3,4 ], object: { "test":"xx" } } )
   11         .then( (r,e) => console.log("greet returned:", r,e));
   12     } else
   13       console.error(error);
   14   });
That's it. Easier and faster than REST or JSON over Http. 

Notable:
  • Client receives the result of a remote call async as ' KPromise '
  • if a method does not return something, the client needs to prepend a '$' like "service.$timeService(..)"
  • There can be only one remoted callback in an argument list and it has to be the last argument

Detailed docs here. Full example source is here.

2


Published in: