pusher-feeds-server v0.8.2
Feeds Server Node reference
This is a server side Node.js library for Feeds service. See the full documentation here
Please note that the reference is annotated with a statically typed dialect like Flow
Importing
Add as a dependency using Yarn or npm.
yarn add pusher-feeds-serverThen import the Feeds constructor.
ES6
// The default export is a Feeds class.
import Feeds from 'pusher-feeds-server';ES5 (CommonJS)
// 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 dashboardkey:string required your key; get this from your dashboard
Example
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
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
feeds
.publish(feed_id, {message: 'Hello World!'})
.then(() => console.log('Succesfully published!'))
.catch((err) => console.log(err));Publish multiple items to a feed
Definition
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
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
feeds.paginate(feedId: string, options: ?PaginateOptions)Arguments
feedId: The feed ID to fetch items from.options: An object with the following keyscursor: ?number: the ID of the first item in the page – if not provided, retrieves the most recently published itemslimit: ?number: the number of items to retrieve, defaults to 50
Returns
Promise of type Promise<PaginateResponse> where PaginateResponse is
items: [Item];
next_cursor: ?string;and Item is
id: string;
created: number;
data: any;Example
Get a page containing the last 25 items of the feed "my-feed".
feeds.paginate("my-feed", { limit: 25 }).then(({ items }) => {
// Do something with each of the items
items.forEach(...);
});Delete all items in a feed
Definition
feeds.delete(feedId: string): Promise<any>Arguments
feedId: The feed ID to delete items in.
Returns
Promise with Node.js http.request IncomingMessage.
Example
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 process diagram and example how to implement this method with collaboration with one of our client side libraries.
Definition
feeds.authorizeFeed(
payload: AuthorizePayload,
hasPermissionCallback: (action: ActionType, feedId: string) => Promise<bool> | bool
): Promise<Object>Arguments
payloadparam is essentially POST request payload (or body) object of typeAuthorizePayload(You can use body-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)
type AuthorizePayload = {
path: string;
action: string;
grant_type: string;
};hasPermissionCallbackparameter 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 abool, or apromiseof one. See the auth-docs for more details.
Returns
A Promise with an authResponse object with the properties listed below which
can then be used for client authorization.
{
access_token: token,
token_type: token_type,
expires_in: token_expiry,
refresh_token: refresh_token
}Example
Using Express.js and body-parser:
// .... 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:
curl -X POST \
-d "action"="READ" \
-d "path"="feeds/private-my-feed-name/items" \
-d "grant_type"="client_credentials" \
http://localhost:5000/feeds/tokensError handling
Since all the public methods on Feeds class returns Promise you should
always call .catch() on it to handle Error properly. pusher-feeds-server
library is using some custom Errors which extends standart JS Error object.
You can import them to your project if would like to use them.
Importing
ES6
import Feeds, {
UnsupportedGrantTypeError,
InvalidGrantTypeError,
ClientError
} from 'pusher-feeds-server';ES5 (CommonJS)
var Feeds = require('pusher-feeds-server');
var UnsupportedGrantTypeError = Feeds.UnsupportedGrantTypeError;
var InvalidGrantTypeError = Feeds.InvalidGrantTypeError;
var ClientError = Feeds.ClientError;