@hitchy/plugin-socket.io

0.1.2 • Public • Published

@hitchy/plugin-socket.io

integrates socket.io server with Hitchy framework

License

MIT

Installation

npm i @hitchy/plugin-socket.io

Usage

The websocket server of socket.io gets automatically integrated with Hitchy on next start of application. The server instance is exposed as api.websocket.

Hitchy's official features are exposed in namespace /hitchy.

Request handling

Hitchy starts listening to connected websocket clients emitting request messages describing requests to be dispatched mostly equivalent to the way regular HTTP requests to Hitchy are handled. Using the websocket is performing slightly better than separate HTTP requests.

On a client, you can use it like this:

io( "/hitchy" ).emit( "request", { 
    method: "POST",
    url: "/api/foo?q=bar",
    headers: { 
        // put request headers here
    },
    body: { 
        // provide some object with your payload data 
    },
}, ( { statusCode, headers, body } ) => {
    // TODO: handle the response
} );

Providing an object as request body is the preferred way. It gets implicitly serialized as JSON body on dispatching the request on server side. The content-type request header may be omitted and must not be set to anything but text/json or application/json. You can also provide a string or ArrayBuffer, in which case any custom content-type request header can be provided, too.

The response body may be data already parsed from a server-side JSON-response.

Custom application: handle requests

On server-side, you can have a service including code like this:

api.websocket.on( "connext", socket => {
    socket.on( "some-request", ( data, response ) => {
        // TODO process `data`, calculate `result`
        
        response( result );
    } );
} );

On client side, you can use that like this:

socket.emit( "some-request", data, result => {
    // TODO process the result
} );

Custom application: respond to server notifications

On server-side, you can emit broadcast notifications like this:

api.websocket.emit( "some-update", data );

On client side, you can receive these notifications like this:

socket.on( "some-update", data => {
    // TODO process the data
} );

Readme

Keywords

Package Sidebar

Install

npm i @hitchy/plugin-socket.io

Weekly Downloads

11

Version

0.1.2

License

MIT

Unpacked Size

10.7 kB

Total Files

9

Last publish

Collaborators

  • soletan
  • simon.friedo