integrates socket.io server with Hitchy framework
npm i @hitchy/plugin-socket.io
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
.
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.
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
} );
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
} );