Skip to content
This repository was archived by the owner on Dec 21, 2021. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"presets": ["env"],
"plugins": ["babel-plugin-add-module-exports",
["transform-runtime", {
"polyfill": false,
"regenerator": true
}]]
}
3 changes: 0 additions & 3 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
# Top-most EditorConfig file
root = true

[*.{js,html}]
indent_style = tab
9 changes: 9 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = exports = {
extends: 'streamr',
rules: {
// Transpiling for node would add a lot of complexity, se let's accept having to write CommonJS modules

'no-plusplus': ["error", { "allowForLoopAfterthoughts": true }],
'no-underscore-dangle': ["error", { "allowAfterThis": true }]
}
}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,5 @@ node_modules
.lock-wscript
.idea
*.iml
.DS_Store
dist/*
122 changes: 94 additions & 28 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
<!-- 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. -->
<a name="js-client"></a>
## Streamr Javascript Client
## Streamr JavaScript Client

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.
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.

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.

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

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

### Usage

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).
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).

#### Creating a StreamrClient instance

```javascript
// Create a StreamrClient instance
var client = new StreamrClient({
// See below for options
// See below for more options
apiKey: 'your-api-key'
})
```

// Subscribe to a stream
#### Subscribing to real-time events in a stream

```javascript
var sub = client.subscribe(
{
stream: 'streamId',
apiKey: 'secret', // Optional. If not given, uses the apiKey given at client creation time.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is breaking change a good idea? At least it would deserve a major version update in npm (npm version major)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My reasoning was this: The name authKey was deprecated, but it is still supported at least until the next major version.

partition: 0, // Optional, defaults to zero. Use for partitioned streams to select partition.
authKey: 'authKey' // Optional. If not given, uses the authKey given at client creation time.
// optional resend options here
},
function(message, metadata) {
// Do something with the message, which is an object
// This is the message handler which gets called for every incoming message in the Stream.
// Do something with the message here!
}
)
```

#### Programmatically creating a Stream

```javascript
client.getOrCreateStream({
name: 'My awesome Stream created via the API',
})
.then((stream) => {
console.log('Stream ' + stream.id + 'has been created!')
// Do something with the Stream
})
```

#### Producing data points to a Stream

```javascript
// Here's our example data point
var msg = {
temperature: 25.4,
humidity: 10,
happy: true
}

// Produce using the Stream id only
client.produceToStream('my-stream-id', msg)

// Or alternatively, via the Stream object (from e.g. getOrCreateStream)
stream.produce(msg)
```

### Client options

Option | Default value | Description
------ | ------------- | -----------
url | wss://www.streamr.com/api/v1/ws | Address of the Streamr websocket endpoint to connect to.
authKey | null | Define default authKey to use when none is specified in the call to `client.subscribe`.
apiKey | null | Define a default apiKey to use when none is specified in the individual function calls.
autoConnect | true | If set to `true`, the client connects automatically on the first call to `subscribe()`. Otherwise an explicit call to `connect()` is required.
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()`.

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

### Methods
### StreamrClient object

#### Connecting

Name | Description
---- | -----------
connect() | Connects to the server, and also subscribes to any streams for which `subscribe()` has been called before calling `connect()`.
disconnect() | Disconnects from the server, clearing all subscriptions.
pause() | Disconnects from the server without clearing subscriptions.

#### Managing subscriptions

Name | Description
---- | -----------
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.
unsubscribe(Subscription) | Unsubscribes the given `Subscription`.
unsubscribeAll(`streamId`) | Unsubscribes all `Subscriptions` for `streamId`.
getSubscriptions(`streamId`) | Returns a list of `Subscriptions` for `streamId`.
bind(eventName, function) | Binds a `function` to an event called `eventName`
unbind(eventName, function) | Unbinds the `function` from events called `eventName`

#### Stream API

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.

Name | Description
---- | -----------
getStream(streamId) | Fetches a Stream object from the API.
listStreams(query) | Fetches an array of Stream objects from the API. For the query params, consult the API docs.
getStreamByName(name) | Fetches a Stream which exactly matches the given name.
createStream(properties) | Creates a Stream with the given properties. For more information on the Stream properties, consult the API docs.
getOrCreateStream(properties) | Gets a Stream with the id or name given in `properties`, or creates it if one is not found.
produceToStream(streamId, message) | Produces a new message (data point) to the given Stream.

#### Listening to state changes of the client

on(eventName, function) | Binds a `function` to an event called `eventName`
once(eventName, function) | Binds a `function` to an event called `eventName`. It gets called once and then removed.
removeListener(eventName, function) | Unbinds the `function` from events called `eventName`

### Stream object

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.

Name | Description
---- | -----------
update() | Updates the properties of this Stream object by sending them to the API.
delete() | Deletes this Stream.
getPermissions() | Returns the list of permissions for this Stream.
detectFields() | Updates the Stream field config (schema) to match the latest data point in the Stream.
produce(message) | Produces a new message (data point) to this Stream.

### Subscription options

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

### Binding to events

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

```javascript
function hello() {
console.log('Hello!')
}

client.bind('connected', hello)
// The StreamrClient emits various events
client.on('connected', function() {
console.log('Yeah, we are connected now!')
})

// So does the Subscription object
var sub = client.subscribe(...)
sub.bind('subscribed', function() {
sub.on('subscribed', function() {
console.log('Subscribed to '+sub.streamId)
})
```

You can unbind using `unbind`:

```javascript
client.unbind('connected', hello)
```


### Events on the StreamrClient instance

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

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

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

In the browser, include `debug.js` and set `localStorage.debug = 'StreamrClient'`
Empty file added dist/.gitkeep
Empty file.
41 changes: 0 additions & 41 deletions examples/node.js

This file was deleted.

41 changes: 41 additions & 0 deletions examples/node/node.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// To enable debug logging:
// DEBUG=StreamrClient node examples/node.js

const StreamrClient = require('streamr-client')

// Create the client with default options
const client = new StreamrClient()

// Subscribe to a stream
const subscription = client.subscribe(
{
stream: '7wa7APtlTq6EC5iTCBy6dw',
// Resend the last 10 messages on connect
resend_last: 10
},
function(message) {
// Handle the messages in this stream
console.log(JSON.stringify(message))
}
)

// Event binding examples
client.on('connected', function() {
console.log('A connection has been established!')
})

subscription.on('subscribed', function() {
console.log('Subscribed to '+subscription.streamId)
})

subscription.on('resending', function() {
console.log('Resending from '+subscription.streamId)
})

subscription.on('resent', function() {
console.log('Resend complete for '+subscription.streamId)
})

subscription.on('no_resend', function() {
console.log('Nothing to resend for '+subscription.streamId)
})
9 changes: 9 additions & 0 deletions examples/node/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "streamr-client-node-example",
"version": "0.0.1",
"description": "Using streamr-client in node",
"main": "node.js",
"dependencies": {
"streamr-client": "0.10.0"
}
}
7 changes: 4 additions & 3 deletions examples/browser.html → examples/web/browser.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<html>
<head>
<!-- For debug messages, include debug.js and set localStorage.debug = 'StreamrClient'. See from https://github.com/visionmedia/debug -->
<script src="../streamr-client.js"></script>
<script src="../../dist/streamr-client.min.js"></script>

<script>
function log(msg) {
Expand All @@ -15,7 +15,7 @@
// Subscribe to a stream
var subscription = client.subscribe(
{
stream: '1ef8TbyGTFiAlZ8R2gCaJw',
stream: '7wa7APtlTq6EC5iTCBy6dw',
// Resend the last 10 messages on connect
resend_last: 10
},
Expand Down Expand Up @@ -45,8 +45,9 @@
subscription.on('no_resend', function() {
log('Nothing to resend for '+subscription.streamId)
})

</script>
</head>
<body>
</body>
</html>
</html>
Loading