Feeds Server Node.js Reference

This is a server side Node.js library for Feeds service. Please note that the reference is annotated with a statically typed dialect like Flow.

Importing

Add as a dependency using yarn or npm.

1
yarn add pusher-feeds-server

Then import the Feeds constructor.

ES6

1
2
// The default export is a Feeds class.
import Feeds from 'pusher-feeds-server';

ES5 (CommonJS)

1
2
// The default export is a Feeds class.
var Feeds = require('pusher-feeds-server');

Instantiate the Feeds Object

Constructor Feeds takes a single options object with the following properties:

  • instanceLocator:string [required] your instance locator; get this from your dashboard
  • key:string [required] your key; get this from your dashboard

Example

1
const feeds = new Feeds({instanceLocator: your_instance_locator, key: your_key});

Publish Single Item to a Feed

Publish an item to a feed, and broadcast the item to all subscribers.

Definition

1
feeds.publish(feedId: string, item: any): Promise<any>

Arguments

  • feedId: The feed ID to publish to. If you publish to a feed that does not exist, it is lazily created.
  • item: Arbitrary JSON representing the item data.

Returns

Promise with Node.js http.request IncomingMessage.

Example

1
2
3
4
feeds
  .publish(feed_id, {message: 'Hello World!'})
  .then(() => console.log('Succesfully published!'))
  .catch((err) => console.log(err));

Publish Multiple Items to a Feed

Definition

1
feeds.publishBatch(feedId: string, items: Array<any>): Promise<any>

Arguments

  • feedId: The feed ID to publish to. If you publish to a feed that does not exist, it is lazily created.
  • items: An array of the data of each item. Items are published into the feed in order from the start of the array.

Returns

Promise with Node.js http.request IncomingMessage.

Example

1
2
3
4
feeds
  .publishBatch(feed_id, [{message: 'Hello A!'}, {message: 'Hello B!'}])
  .then(() => console.log('Succesfully published!'))
  .catch((err) => console.log(err));

Pagination

Query a feed for pages of previously published items. Items are returned in descending order of item ID.

Definition

1
feeds.paginate(feedId: string, options: ?PaginateOptions)

Arguments

  • feedId: The feed ID to fetch items from.
  • options: An object with the following keys
    • cursor: ?number: the ID of the first item in the page – if not provided, retrieves the most recently published items
    • limit: ?number: the number of items to retrieve, defaults to 50

Returns

Promise of type Promise<PaginateResponse> where PaginateResponse is

1
2
items: [Item];
next_cursor: ?string;

and Item is

1
2
3
id: string;
created: number;
data: any;

Example

Get a page containing the last 25 items of the feed "my-feed".

1
2
3
4
feeds.paginate("my-feed", { limit: 25 }).then(({ items }) => {
  // Do something with each of the items
  items.forEach(...);
});

Delete All Items in a Feed

Definition

1
feeds.delete(feedId: string): Promise<any>

Arguments

  • feedId: The feed ID to delete items in.

Returns

Promise with Node.js http.request IncomingMessage.

Example

1
2
3
feeds.delete('newsfeed')
  .then(() => console.log('Succesfully deleted!'))
  .catch((err) => console.log(err));

Authorize Clients to Access Private Feeds

This method allows you to authorize your clients for access to a certain feed. Please see auth processdiagramand example how to implement this method with collaboration with one of our client side libraries.

Definition

1
2
3
4
feeds.authorizeFeed(
  payload: AuthorizePayload,
  hasPermissionCallback: (action: ActionType, feedId: string) => Promise<bool> | bool
): Promise<Object>

Arguments

  • payload param is essentially POST request payload (or body) object of typeAuthorizePayload (You can usebody-parser to parse the POST request body for you). The object must have the following format: (Please note that if you using one of our client libraries they will handle this format for you)
1
2
3
4
5
type AuthorizePayload = {
  path: string;
  action: string;
  grant_type: string;
};
  • hasPermissionCallback parameter allows you to grant or deny permission to access a feed based on any information you have in scope (e.g. session data). It should either return a bool, or a promise of one. See theauth-docsfor more details.

Returns

A Promise with an authResponse object with the properties listed below which can then be used for client authorization.

1
2
3
4
5
6
{
  access_token: token,
  token_type: token_type,
  expires_in: token_expiry,
  refresh_token: refresh_token
}

Example

Using Express.js and body-parser:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// .... Init express js server
// Register auth endpoint
app.post('/feeds/tokens', (req, res) => {
  // Define hasPermission to be used in authorizeFeed function
  const hasPermission = (action, feedId) => (
    db.find(req.session.userId)
      .then(userId => userId === 'abcd')
  );

  // Authorize user with request payload and hasPermission callback.
  feeds.authorizeFeed(req, hasPermission)
    .then(data => res.send(data))
    .catch(err => {
      res.status(400).send(`${err.name}: ${err.message}`)
    });
});

considering that we have the Express.js http server running on http://localhost:5000 then we can test the auth endpoint with curl:

1
2
3
4
5
curl -X POST \
-d "action"="READ" \
-d "path"="feeds/private-my-feed-name/items" \
-d "grant_type"="client_credentials" \
http://localhost:5000/feeds/tokens

Error Handling

Since all the public methods on Feeds class returns Promise you should always call .catch() on it to handle Error properly. pusher-feeds-serverlibrary is using some custom Errors which extends standart JS Error object. You can import them to your project if would like to use them.

ES6

1
2
3
4
5
import Feeds, {
  UnsupportedGrantTypeError,
  InvalidGrantTypeError,
  ClientError
} from 'pusher-feeds-server';

ES5 (CommonJS)

1
2
3
4
var Feeds = require('pusher-feeds-server');
var UnsupportedGrantTypeError = Feeds.UnsupportedGrantTypeError;
var InvalidGrantTypeError = Feeds.InvalidGrantTypeError;
var ClientError = Feeds.ClientError;

Did you find this document useful?

We are always striving to create the most accurate and informative docs as possible. If there is something especially wrong (or right) here then please let us know.