0.0.3 • Published 7 years ago

@cameronwp/client-endpoint v0.0.3

Weekly downloads
1
License
MIT
Repository
github
Last release
7 years ago

Client Endpoint

The client side of simplified socket.io messaging.

See also @cameronwp/server-endpoint. Testing happens in @cameronwp/server-endpoint.

npm i -S @cameronwp/client-endpoint

Sample Usage

All examples assume that on{message,request} handlers were set before any {message,request} were sent.

// server.js
const ServerEndpoint = require('@cameronwp/server-endpoint');

const port = 8000;
const server = new ServerEndpoint(port);
const namespace = server.createNamespace('chat'); // create as many namespaces as you want

// example server -> client push
namespace.pushMessage('new-message', 'lorem ipsum...');

// example client -> server post
namespace.onmessage('config-change', val => {
    console.log(JSON.stringify(val)); // logs "{config: 'object'}"
});

// example server response to a request
namespace.onrequest('test-request', 'ack');

// example server responding to a request with a function
namespace.onrequest('test-request-doubler-function', data => {
  return data * 2;
});
// client.js
const ClientEndpoint = require('@cameronwp/client-endpoint');

const client = new ClientEndpoint('http://localhost:8000/chat');  // note the port and "/chat" namespace

// example server -> client push
client.onmessage('new-message', val => {
    console.log(val); // logs "lorem ipsum..."
});

// example client -> server post
client.postMessage('config-change', {config: 'object'});

// example server response to a request
client.request('test-request').then(console.log); // logs "ack"

// example server response to a request
client.request('test-request-doubler-function', 2).then(console.log); // logs 4

API

ClientEndpoint ⇐ Endpoint

Kind: global class Extends: Endpoint

new ClientEndpoint(location)

Exposes a wrapper around a socket.io client connection to a server.

ParamType
locationstring

clientEndpoint.postMessage(type, data) ⇒ Promise

Post a message to the server. Resolves when the message is acknowledged. Nothing is sent to the acknowledgement.

Kind: instance method of ClientEndpoint Returns: Promise - Promise that resolves when the server acknowledges the message.

ParamTypeDescription
typestringType of message to send to the server.
data*Contents of the message.

clientEndpoint.request(type, key) ⇒ Promise

Send a request. Returns a promise that resolves to the response.

Kind: instance method of ClientEndpoint Returns: Promise - Promise that receives the response.

ParamTypeDescription
typestringInfo you are requesting.
keystringnconf style key