Skip to content
This repository was archived by the owner on Dec 21, 2021. It is now read-only.

Commit 80bfc39

Browse files
authored
CORE-1242, CORE-1243, CORE-1244 Webpack and Stream API (#13)
* installed webpack and es6-ified everything * to make websockets work, use separate builds for node and web * tweaks for running tests * delete unused dist files * add rest endpoint files * add restUrl option * works otherwise but fetch is missing from node * added node-fetch + its shim for browser * add integration tests, fix bugs * build * change author to 'Streamr' * rename authKey to apiKey in README * refactor Subscription state, update eslint rules * Update readme, remove public read permission manipulation as that will become quite redundant after marketplace * delete files in dist * dist added to .gitignore * fix webpack use of this module by adding 'module' field to package.json * fall back to commonjs modules and drop node build
1 parent 52eded4 commit 80bfc39

28 files changed

+10974
-2654
lines changed

.babelrc

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"presets": ["env"],
3+
"plugins": ["babel-plugin-add-module-exports",
4+
["transform-runtime", {
5+
"polyfill": false,
6+
"regenerator": true
7+
}]]
8+
}

.editorconfig

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,2 @@
11
# Top-most EditorConfig file
22
root = true
3-
4-
[*.{js,html}]
5-
indent_style = tab

.eslintrc.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
module.exports = exports = {
2+
extends: 'streamr',
3+
rules: {
4+
// Transpiling for node would add a lot of complexity, se let's accept having to write CommonJS modules
5+
6+
'no-plusplus': ["error", { "allowForLoopAfterthoughts": true }],
7+
'no-underscore-dangle': ["error", { "allowAfterThis": true }]
8+
}
9+
}

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,5 @@ node_modules
2828
.lock-wscript
2929
.idea
3030
*.iml
31+
.DS_Store
32+
dist/*

README.md

Lines changed: 94 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
<!-- Note that this readme is embedded on API Documentation page within Streamr. Please don't use first-level headings (h1). You should write this document so that it will work both as a stand-alone document in the public GitHub repo and as a section in the API docs. -->
22
<a name="js-client"></a>
3-
## Streamr Javascript Client
3+
## Streamr JavaScript Client
44

5-
By using this client, you can easily subscribe to realtime [Streamr](http://www.streamr.com) streams from Javascript-based environments, such as browsers and [node.js](https://nodejs.org). This enables you to use Streamr as an over-the-internet pub/sub engine with powerful analytics and automation features.
5+
By using this client, you can easily interact with the [Streamr](http://www.streamr.com) API from JavaScript-based environments, such as browsers and [node.js](https://nodejs.org). You can, for example, subscribe to real-time data in Streams, produce new data to Streams, and create new Streams.
6+
7+
This library is work-in-progress and doesn't provide wrapper functions for all the endpoints in the Streamr API. Currently it covers producing and subscribing to data as well as manipulating Stream objects.
68

79
The client uses websockets for streaming message delivery. It should work in all modern browsers.
810

@@ -14,34 +16,69 @@ The client is available on [npm](https://www.npmjs.com/package/streamr-client) a
1416

1517
### Usage
1618

17-
Here's a quick example. More detailed examples for the browser and node.js can be found [here](https://github.com/streamr-dev/streamr-client/tree/master/examples).
19+
Here are some quick examples. More detailed examples for the browser and node.js can be found [here](https://github.com/streamr-dev/streamr-client/tree/master/examples).
20+
21+
#### Creating a StreamrClient instance
1822

1923
```javascript
20-
// Create a StreamrClient instance
2124
var client = new StreamrClient({
22-
// See below for options
25+
// See below for more options
26+
apiKey: 'your-api-key'
2327
})
28+
```
2429

25-
// Subscribe to a stream
30+
#### Subscribing to real-time events in a stream
31+
32+
```javascript
2633
var sub = client.subscribe(
2734
{
2835
stream: 'streamId',
36+
apiKey: 'secret', // Optional. If not given, uses the apiKey given at client creation time.
2937
partition: 0, // Optional, defaults to zero. Use for partitioned streams to select partition.
30-
authKey: 'authKey' // Optional. If not given, uses the authKey given at client creation time.
3138
// optional resend options here
3239
},
3340
function(message, metadata) {
34-
// Do something with the message, which is an object
41+
// This is the message handler which gets called for every incoming message in the Stream.
42+
// Do something with the message here!
3543
}
3644
)
3745
```
3846

47+
#### Programmatically creating a Stream
48+
49+
```javascript
50+
client.getOrCreateStream({
51+
name: 'My awesome Stream created via the API',
52+
})
53+
.then((stream) => {
54+
console.log('Stream ' + stream.id + 'has been created!')
55+
// Do something with the Stream
56+
})
57+
```
58+
59+
#### Producing data points to a Stream
60+
61+
```javascript
62+
// Here's our example data point
63+
var msg = {
64+
temperature: 25.4,
65+
humidity: 10,
66+
happy: true
67+
}
68+
69+
// Produce using the Stream id only
70+
client.produceToStream('my-stream-id', msg)
71+
72+
// Or alternatively, via the Stream object (from e.g. getOrCreateStream)
73+
stream.produce(msg)
74+
```
75+
3976
### Client options
4077

4178
Option | Default value | Description
4279
------ | ------------- | -----------
4380
url | wss://www.streamr.com/api/v1/ws | Address of the Streamr websocket endpoint to connect to.
44-
authKey | null | Define default authKey to use when none is specified in the call to `client.subscribe`.
81+
apiKey | null | Define a default apiKey to use when none is specified in the individual function calls.
4582
autoConnect | true | If set to `true`, the client connects automatically on the first call to `subscribe()`. Otherwise an explicit call to `connect()` is required.
4683
autoDisconnect | true  | If set to `true`, the client automatically disconnects when the last stream is unsubscribed. Otherwise the connection is left open and can be disconnected explicitly by calling `disconnect()`.
4784

@@ -54,19 +91,55 @@ Argument | Description
5491
message | A javascript object containing the message itself
5592
metadata | Metadata for the message, for example `metadata.timestamp` etc.
5693

57-
### Methods
94+
### StreamrClient object
95+
96+
#### Connecting
5897

5998
Name | Description
6099
---- | -----------
61100
connect() | Connects to the server, and also subscribes to any streams for which `subscribe()` has been called before calling `connect()`.
62101
disconnect() | Disconnects from the server, clearing all subscriptions.
63102
pause() | Disconnects from the server without clearing subscriptions.
103+
104+
#### Managing subscriptions
105+
106+
Name | Description
107+
---- | -----------
64108
subscribe(options, callback) | Subscribes to a stream. Messages in this stream are passed to the `callback` function. See below for subscription options. Returns a `Subscription` object.
65109
unsubscribe(Subscription) | Unsubscribes the given `Subscription`.
66110
unsubscribeAll(`streamId`) | Unsubscribes all `Subscriptions` for `streamId`.
67111
getSubscriptions(`streamId`) | Returns a list of `Subscriptions` for `streamId`.
68-
bind(eventName, function) | Binds a `function` to an event called `eventName`
69-
unbind(eventName, function) | Unbinds the `function` from events called `eventName`
112+
113+
#### Stream API
114+
115+
All the below functions return a Promise which gets resolved with the result. They can also take an `apiKey` as an extra argument. Otherwise the `apiKey` defined in the `StreamrClient` options is used, if any.
116+
117+
Name | Description
118+
---- | -----------
119+
getStream(streamId) | Fetches a Stream object from the API.
120+
listStreams(query) | Fetches an array of Stream objects from the API. For the query params, consult the API docs.
121+
getStreamByName(name) | Fetches a Stream which exactly matches the given name.
122+
createStream(properties) | Creates a Stream with the given properties. For more information on the Stream properties, consult the API docs.
123+
getOrCreateStream(properties) | Gets a Stream with the id or name given in `properties`, or creates it if one is not found.
124+
produceToStream(streamId, message) | Produces a new message (data point) to the given Stream.
125+
126+
#### Listening to state changes of the client
127+
128+
on(eventName, function) | Binds a `function` to an event called `eventName`
129+
once(eventName, function) | Binds a `function` to an event called `eventName`. It gets called once and then removed.
130+
removeListener(eventName, function) | Unbinds the `function` from events called `eventName`
131+
132+
### Stream object
133+
134+
All the below functions return a Promise which gets resolved with the result. They can also take an `apiKey` as an extra argument. Otherwise the `apiKey` defined in the `StreamrClient` options is used, if any.
135+
136+
Name | Description
137+
---- | -----------
138+
update() | Updates the properties of this Stream object by sending them to the API.
139+
delete() | Deletes this Stream.
140+
getPermissions() | Returns the list of permissions for this Stream.
141+
detectFields() | Updates the Stream field config (schema) to match the latest data point in the Stream.
142+
produce(message) | Produces a new message (data point) to this Stream.
70143

71144
### Subscription options
72145

@@ -75,7 +148,7 @@ Note that only one of the resend options can be used for a particular subscripti
75148
Name | Description
76149
---- | -----------
77150
stream | Stream id to subscribe to
78-
authKey | User key or stream key that authorizes the subscription. If defined, overrides the client's `authKey`.
151+
apiKey | User key or stream key that authorizes the subscription. If defined, overrides the client's `apiKey`.
79152
partition | Partition number to subscribe to. Defaults to the default partition (0).
80153
resend_all | Set to `true` if you want all the messages for the stream resent from the earliest available message.
81154
resend_last | Resend the previous `N` messages.
@@ -85,28 +158,21 @@ resend_to | Can be used in conjunction with `resend_from` to limit the end of th
85158

86159
### Binding to events
87160

88-
The client and the subscriptions can fire events as detailed below. You can bind to them using `bind`:
161+
The client and the subscriptions can fire events as detailed below. You can bind to them using `on`:
89162

90163
```javascript
91-
function hello() {
92-
console.log('Hello!')
93-
}
94-
95-
client.bind('connected', hello)
164+
// The StreamrClient emits various events
165+
client.on('connected', function() {
166+
console.log('Yeah, we are connected now!')
167+
})
96168

169+
// So does the Subscription object
97170
var sub = client.subscribe(...)
98-
sub.bind('subscribed', function() {
171+
sub.on('subscribed', function() {
99172
console.log('Subscribed to '+sub.streamId)
100173
})
101174
```
102175

103-
You can unbind using `unbind`:
104-
105-
```javascript
106-
client.unbind('connected', hello)
107-
```
108-
109-
110176
### Events on the StreamrClient instance
111177

112178
Name | Handler Arguments | Description
@@ -128,6 +194,6 @@ no_resend | | Fired after `resending` in case there was nothing to resend.
128194

129195
The Streamr JS client library supports [debug](https://github.com/visionmedia/debug) for logging.
130196

131-
In node.js, start your app like this: `DEBUG=StreamrClient node your-app.js`
197+
In node.js, start your app like this: `DEBUG=StreamrClient* node your-app.js`
132198

133199
In the browser, include `debug.js` and set `localStorage.debug = 'StreamrClient'`

dist/.gitkeep

Whitespace-only changes.

examples/node.js

Lines changed: 0 additions & 41 deletions
This file was deleted.

examples/node/node.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// To enable debug logging:
2+
// DEBUG=StreamrClient node examples/node.js
3+
4+
const StreamrClient = require('streamr-client')
5+
6+
// Create the client with default options
7+
const client = new StreamrClient()
8+
9+
// Subscribe to a stream
10+
const subscription = client.subscribe(
11+
{
12+
stream: '7wa7APtlTq6EC5iTCBy6dw',
13+
// Resend the last 10 messages on connect
14+
resend_last: 10
15+
},
16+
function(message) {
17+
// Handle the messages in this stream
18+
console.log(JSON.stringify(message))
19+
}
20+
)
21+
22+
// Event binding examples
23+
client.on('connected', function() {
24+
console.log('A connection has been established!')
25+
})
26+
27+
subscription.on('subscribed', function() {
28+
console.log('Subscribed to '+subscription.streamId)
29+
})
30+
31+
subscription.on('resending', function() {
32+
console.log('Resending from '+subscription.streamId)
33+
})
34+
35+
subscription.on('resent', function() {
36+
console.log('Resend complete for '+subscription.streamId)
37+
})
38+
39+
subscription.on('no_resend', function() {
40+
console.log('Nothing to resend for '+subscription.streamId)
41+
})

examples/node/package.json

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"name": "streamr-client-node-example",
3+
"version": "0.0.1",
4+
"description": "Using streamr-client in node",
5+
"main": "node.js",
6+
"dependencies": {
7+
"streamr-client": "0.10.0"
8+
}
9+
}

examples/browser.html renamed to examples/web/browser.html

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<html>
22
<head>
33
<!-- For debug messages, include debug.js and set localStorage.debug = 'StreamrClient'. See from https://github.com/visionmedia/debug -->
4-
<script src="../streamr-client.js"></script>
4+
<script src="../../dist/streamr-client.min.js"></script>
55

66
<script>
77
function log(msg) {
@@ -15,7 +15,7 @@
1515
// Subscribe to a stream
1616
var subscription = client.subscribe(
1717
{
18-
stream: '1ef8TbyGTFiAlZ8R2gCaJw',
18+
stream: '7wa7APtlTq6EC5iTCBy6dw',
1919
// Resend the last 10 messages on connect
2020
resend_last: 10
2121
},
@@ -45,8 +45,9 @@
4545
subscription.on('no_resend', function() {
4646
log('Nothing to resend for '+subscription.streamId)
4747
})
48+
4849
</script>
4950
</head>
5051
<body>
5152
</body>
52-
</html>
53+
</html>

0 commit comments

Comments
 (0)