1 | ;
|
2 |
|
3 | import {
|
4 | modClientid,
|
5 | modStringify,
|
6 | modPublish,
|
7 | modInfo,
|
8 | modSubscribe
|
9 | } from './modules/core/index';
|
10 |
|
11 | /**
|
12 | * Creates a new CatSnake client.
|
13 | * @class
|
14 | */
|
15 | class CatSnake {
|
16 | /**
|
17 | * @constructs CatSnake
|
18 | * @param {string} address - the address of the catsnake server
|
19 | * @param {object} options - options such as common name and others
|
20 | */
|
21 | constructor(address, options) {
|
22 | this.socket = new WebSocket(address);
|
23 | this.connected = false;
|
24 | this.client = this.clientid();
|
25 | this.commonName = (options.commonName) ?
|
26 | options.commonName : 'A Random Postman.';
|
27 |
|
28 | // Fired when the connection is made to the server
|
29 | this.socket.onopen = event => {
|
30 | this.connected = true;
|
31 |
|
32 | // Make sure we tell the server we're leaving.
|
33 | window.onbeforeunload = () => {
|
34 | this.socket.close();
|
35 | };
|
36 | };
|
37 | }
|
38 |
|
39 | static clientid() {
|
40 | /**
|
41 | * Returns a new random, unique clientid
|
42 | * @function modClientid
|
43 | * @return {string} - Returns a new random, unique clientid
|
44 | */
|
45 | return modClientid();
|
46 | }
|
47 |
|
48 | static stringify(data, callback) {
|
49 | /**
|
50 | * Tries to return a stringified object.
|
51 | * @function modStringify
|
52 | * @param {object} data - the object to attempt to stringify
|
53 | * @callback {string} - Returns a stringified object
|
54 | */
|
55 | return modStringify(data, callback);
|
56 | }
|
57 |
|
58 | publish(channel, data, privateKey) {
|
59 | /**
|
60 | * Publishes a message to all subscribers
|
61 | * @function modPublish
|
62 | * @param {string} channel - the channel to publish to
|
63 | * @param {object} data - the object to publish
|
64 | * @param {string} privateKey - optional private key for private channels
|
65 | * @param {this} this - this inheratance
|
66 | */
|
67 | modPublish(channel, data, privateKey, this);
|
68 | }
|
69 |
|
70 | info(channel, data, opts) {
|
71 | /**
|
72 | * List all clients
|
73 | * @function modInfo
|
74 | * @param {string} channel - the channel to look at
|
75 | * @param {object} data - additional information for request
|
76 | * @param {object} opts - additional options for subscriptions
|
77 | * @param {this} this - this inheratance
|
78 | */
|
79 | modInfo(channel, data, opts, this);
|
80 | }
|
81 |
|
82 | subscribe(channel, callback, opts) {
|
83 | /**
|
84 | * Subscribe to a channel
|
85 | * @function modSubscribe
|
86 | * @param {string} channel - the channel to subscribe to
|
87 | * @callback {function} callback - new messages are returned here via msg
|
88 | * @param {object} opts - additional options for subscriptions
|
89 | * @param {this} this - this inheratance
|
90 | */
|
91 | modSubscribe(channel, callback, opts, this);
|
92 | }
|
93 | }
|