GithubHelp home page GithubHelp logo

getstream / stream-js Goto Github PK

View Code? Open in Web Editor NEW
325.0 37.0 109.0 7.97 MB

JS / Browser Client - Build Activity Feeds & Streams with GetStream.io

Home Page: https://getstream.io

License: BSD 3-Clause "New" or "Revised" License

JavaScript 66.10% TypeScript 33.72% HTML 0.18%
javascript stream-js activity-feed getstream notification-feed news-feed feed timeline

stream-js's Introduction

Official JavaScript SDK for Stream Feeds

build NPM

Official JavaScript API client for Stream Feeds, a web service for building scalable newsfeeds and activity streams.
Explore the docs »

Report Bug · Request Feature

📝 About Stream

stream-js is the official JavaScript client for Stream, a web service for building scalable newsfeeds and activity streams.

Note that there is also a higher level Node integration which hooks into your ORM.

You can sign up for a Stream account at https://getstream.io/get_started.

💡 Note: this is a library for the Feeds product. The Chat SDKs can be found here.

⚙️ Installation

Install from NPM/YARN

npm install getstream

or if you are using yarn

yarn add getstream

Using JS deliver

<script src="https://cdn.jsdelivr.net/npm/getstream/dist/js_min/getstream.js"></script>

⚠️ This will pull the latest which can be breaking for your application. Always pin a specific version as follows:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js_min/getstream.js"></script>

Install by downloading the JS file

JS / Minified JS

⚠️ Beware about the version you're pulling. It's the latest by default which can break your app anytime.

📚 Full documentation

Documentation for this JavaScript client are available at the Stream website.

Using with React Native

This package can be integrated into React Native applications. Remember to not expose the App Secret in browsers, "native" mobile apps, or other non-trusted environments.

✨ Getting started

API client setup Node

import { connect } from 'getstream';
// or if you are on commonjs
const { connect } = require('getstream');

// Instantiate a new client (server side)
const client = connect('YOUR_API_KEY', 'API_KEY_SECRET');
// Optionally supply the app identifier and an options object specifying the data center to use and timeout for requests (15s)
const client = connect('YOUR_API_KEY', 'API_KEY_SECRET', 'APP_ID', { location: 'us-east', timeout: 15000 });

API client setup Node + Browser

If you want to use the API client directly on your web/mobile app you need to generate a user token server-side and pass it.

Server-side token generation

import { connect } from 'getstream';
// or if you are on commonjs
const { connect } = require('getstream');

// Instantiate a new client (server side)
const client = connect('YOUR_API_KEY', 'API_KEY_SECRET');
// Optionally supply the app identifier and an options object specifying the data center to use and timeout for requests (15s)
const client = connect('YOUR_API_KEY', 'API_KEY_SECRET', 'APP_ID', { location: 'us-east', timeout: 15000 });
// Create a token for user with id "the-user-id"
const userToken = client.createUserToken('the-user-id');

⚠️ Client checks if it's running in a browser environment with a secret and throws an error for a possible security issue of exposing your secret. If you are running backend code in Google Cloud or you know what you're doing, you can specify browser: false in options to skip this check.

const client = connect('YOUR_API_KEY', 'API_KEY_SECRET', 'APP_ID', { browser: false });

Client API init

import { connect } from 'getstream';
// or if you are on commonjs
const { connect } = require('getstream');
// Instantiate new client with a user token
const client = connect('apikey', userToken, 'appid');

Examples

// Instantiate a feed object server side
user1 = client.feed('user', '1');

// Get activities from 5 to 10 (slow pagination)
user1.get({ limit: 5, offset: 5 });
// Filter on an id less than a given UUID
user1.get({ limit: 5, id_lt: 'e561de8f-00f1-11e4-b400-0cc47a024be0' });

// All API calls are performed asynchronous and return a Promise object
user1
  .get({ limit: 5, id_lt: 'e561de8f-00f1-11e4-b400-0cc47a024be0' })
  .then(function (body) {
    /* on success */
  })
  .catch(function (reason) {
    /* on failure, reason.error contains an explanation */
  });

// Create a new activity
activity = { actor: 1, verb: 'tweet', object: 1, foreign_id: 'tweet:1' };
user1.addActivity(activity);
// Create a bit more complex activity
activity = {
  actor: 1,
  verb: 'run',
  object: 1,
  foreign_id: 'run:1',
  course: { name: 'Golden Gate park', distance: 10 },
  participants: ['Thierry', 'Tommaso'],
  started_at: new Date(),
};
user1.addActivity(activity);

// Remove an activity by its id
user1.removeActivity('e561de8f-00f1-11e4-b400-0cc47a024be0');
// or remove by the foreign id
user1.removeActivity({ foreign_id: 'tweet:1' });

// mark a notification feed as read
notification1 = client.feed('notification', '1');
params = { mark_read: true };
notification1.get(params);

// mark a notification feed as seen
params = { mark_seen: true };
notification1.get(params);

// Follow another feed
user1.follow('flat', '42');

// Stop following another feed
user1.unfollow('flat', '42');

// Stop following another feed while keeping previously published activities
// from that feed
user1.unfollow('flat', '42', { keepHistory: true });

// Follow another feed without copying the history
user1.follow('flat', '42', { limit: 0 });

// List followers, following
user1.followers({ limit: '10', offset: '10' });
user1.following({ limit: '10', offset: '0' });

user1.follow('flat', '42');

// adding multiple activities
activities = [
  { actor: 1, verb: 'tweet', object: 1 },
  { actor: 2, verb: 'tweet', object: 3 },
];
user1.addActivities(activities);

// specifying additional feeds to push the activity to using the to param
// especially useful for notification style feeds
to = ['user:2', 'user:3'];
activity = {
  to: to,
  actor: 1,
  verb: 'tweet',
  object: 1,
  foreign_id: 'tweet:1',
};
user1.addActivity(activity);

// adding one activity to multiple feeds
feeds = ['flat:1', 'flat:2', 'flat:3', 'flat:4'];
activity = {
  actor: 'User:2',
  verb: 'pin',
  object: 'Place:42',
  target: 'Board:1',
};

// ⚠️ server-side only!
client.addToMany(activity, feeds);

// Batch create follow relations (let flat:1 follow user:1, user:2 and user:3 feeds in one single request)
follows = [
  { source: 'flat:1', target: 'user:1' },
  { source: 'flat:1', target: 'user:2' },
  { source: 'flat:1', target: 'user:3' },
];

// ⚠️ server-side only!
client.followMany(follows);

// Updating parts of an activity
set = {
  'product.price': 19.99,
  shares: {
    facebook: '...',
    twitter: '...',
  },
};
unset = ['daily_likes', 'popularity'];
// ...by ID
client.activityPartialUpdate({
  id: '54a60c1e-4ee3-494b-a1e3-50c06acb5ed4',
  set: set,
  unset: unset,
});
// ...or by combination of foreign ID and time
client.activityPartialUpdate({
  foreign_id: 'product:123',
  time: '2016-11-10T13:20:00.000000',
  set: set,
  unset: unset,
});

// ⚠️ server-side only!
// Create redirect urls
impression = {
  content_list: ['tweet:1', 'tweet:2', 'tweet:3'],
  user_data: 'tommaso',
  location: 'email',
  feed_id: 'user:global',
};
engagement = {
  content: 'tweet:2',
  label: 'click',
  position: 1,
  user_data: 'tommaso',
  location: 'email',
  feed_id: 'user:global',
};
events = [impression, engagement];
redirectUrl = client.createRedirectUrl('http://google.com', 'user_id', events);

// update the 'to' fields on an existing activity
// client.feed("user", "ken").function (foreign_id, timestamp, new_targets, added_targets, removed_targets)
// new_targets, added_targets, and removed_targets are all arrays of feed IDs
// either provide only the `new_targets` parameter (will replace all targets on the activity),
// OR provide the added_targets and removed_targets parameters
// NOTE - the updateActivityToTargets method is not intended to be used in a browser environment.
client.feed('user', 'ken').updateActivityToTargets('foreign_id:1234', timestamp, ['feed:1234']);
client.feed('user', 'ken').updateActivityToTargets('foreign_id:1234', timestamp, null, ['feed:1234']);
client.feed('user', 'ken').updateActivityToTargets('foreign_id:1234', timestamp, null, null, ['feed:1234']);

Typescript

import { connect, UR, EnrichedActivity, NotificationActivity } from 'getstream';

type User1Type = { name: string; username: string; image?: string };
type User2Type = { name: string; avatar?: string };
type ActivityType = { attachments: string[]; text: string };
type Collection1Type = { cid: string; rating?: number };
type Collection2Type = { branch: number; location: string };

type ReactionType = { text: string };
type ChildReactionType = { text?: string };

type StreamType = {
  userType: User1Type | User2Type,
  activityType: ActivityType,
  collectionType: Collection1Type | Collection2Type,
  reactionType: ReactionType,
  childReactionType: ChildReactionType,
  personalizationType: UR,
}

const client = connect<StreamType>('api_key', 'secret!', 'app_id');

// if you have different union types like "User1Type | User2Type" you can use type guards as follow:
// https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types
function isUser1Type(user: User1Type | User2Type): user is User1Type {
  return (user as User1Type).username !== undefined;
}

client
  .user('user_id')
  .get()
  .then((user) => {
    const { data, id } = user;
    if (isUser1Type(data)) return data.username;
    return id;
  });

// notification: StreamFeed<StreamType>
const timeline = client.feed('timeline', 'feed_id');
timeline.get({ withOwnChildren: true, withOwnReactions: true }).then((response) => {
  // response: FeedAPIResponse<StreamType>
  if (response.next !== '') return response.next;

  return (response.results as EnrichedActivity<StreamType>[]).map((activity) => {
    return activity.id + activity.text + (activity.actor as User2Type).name;
  });
});

// notification: StreamFeed<StreamType>
const notification = client.feed('notification', 'feed_id');
notification.get({ mark_read: true, mark_seen: true }).then((response) => {
  // response: FeedAPIResponse<StreamType>
  if (response.unread || response.unseen) return response.next;

  return (response.results as NotificationActivity<ActivityType>[]).map((activityGroup) => {
    const { activities, id, verb, activity_count, actor_count } = activityGroup;
    return activities[0].text + id + actor_count + activity_count + verb;
  });
});

client.collections.get('collection_1', 'taco').then((item: CollectionEntry<StreamType>) => {
  if (item.data.rating) return { [item.data.cid]: item.data.rating };
  return item.id;
});

Realtime (Faye)

Stream uses Faye for realtime notifications. Below is quick guide to subscribing to feed changes

const { connect } = require('getstream');

// ⚠️ userToken is generated server-side (see previous section)
const client = connect('YOUR_API_KEY', userToken, 'APP_ID');
const user1 = client.feed('user', '1');

// subscribe to the changes
const subscription = user1.subscribe(function (data) {
  console.log(data);
});
// now whenever something changes to the feed user 1
// the callback will be called

// To cancel a subscription you can call cancel on the
// object returned from a subscribe call.
// This will remove the listener from this channel.
subscription.cancel();

Docs are available on GetStream.io.

⚠️ Node version requirements & Browser support

This API Client project requires Node.js v16 at a minimum.

The project is supported in line with the Node.js Foundation Release Working Group.

See the github action configuration for details of how it is built, tested and packaged.

♻️ Contributing

See extensive at test documentation for your changes.

You can find generic API documentation enriched by code snippets from this package at http://getstream.io/docs/?language=js

Copyright and License Information

Project is licensed under the BSD 3-Clause.

We welcome code changes that improve this library or fix a problem, please make sure to follow all best practices and add tests if applicable before submitting a Pull Request on Github. We are very happy to merge your code in the official repository. Make sure to sign our Contributor License Agreement (CLA) first. See our license file for more details.

🧑‍💻 We are hiring!

We've recently closed a $38 million Series B funding round and we keep actively growing. Our APIs are used by more than a billion end-users, and you'll have a chance to make a huge impact on the product within a team of the strongest engineers all over the world.

Check out our current openings and apply via Stream's website.

stream-js's People

Contributors

berkerpeksag avatar brabster avatar dependabot[bot] avatar dwightgunning avatar ferhatelmas avatar github-actions[bot] avatar hannesvdvreken avatar jeltef avatar kenhoff avatar mahboubii avatar marciopuga avatar martincupela avatar matthisk avatar mgom avatar mircea-cosbuc avatar nickjanssen avatar nima-lighthouse avatar nwoltman avatar oliverjash avatar peterdeme avatar ruggi avatar ruudniew avatar sanjaytwisk avatar tbarbugli avatar tobiasbueschel avatar tschellenbach avatar tyleraholden avatar vagruchi avatar vanm avatar xernobyl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stream-js's Issues

Issue with TARGETTING & "TO" SUPPORT

I was exploring "Targetting & To Supports" of your wonderful platform.
Every time, I insert new activity with "to" field, I get following error messge:

"detail": "Errors for fields 'to'",
"duration": "7ms",
"exception": "InputException",
"exception_fields": {
"to": [
{
"0": [
"Invalid value."
]
}
]
},
"status_code": 400

Without "to", it works fine.

This is how I am inserting new activity to user feed:
var streamActivityObj={
.....
verb: obj.verb,
object: {
content: obj.content,
object_type: obj.object_type
},
target: obj.target,
to: ["flat:5648e69f40d7a92b71fc9690"],
foreign_id: some_id,
....
}
//Insert to ufeeds....
var currentActorFeed = con.uFeeds[kinId];
currentActorFeed.addActivity(streamActivityObj, function (errorAddingActivity, responseAddingActivity, bodyAddingActivity) {
if (errorAddingActivity) {
return cb(errorAddingActivity, null);

I tried debugging, and it seems that the flatfeed is valid as well.
Dump of flatfeed for userId= 5648e69f40d7a92b71fc9690

node: true }, slug: 'flat', userId: '5648e69f40d7a92b71fc9690', id: 'flat:5648e69f40d7a92b71fc9690', token: 'mxcxmcxmnmcxnxcmnxcncncxmnxcmcnx'fake', feedUrl: 'flat/5648e69f40d7a92b71fc9690', feedTogether: 'flat5648e69f40d7a92b71fc9690',
..........................................

Could you please help me in this regard?

Thanks.

support for private feeds

send target_token as part of post body containing the signature token of the target feed id (eg. secret:42)

the test account has a private feed configured (slug secret)

Requiring getstream on the frontend

Right now if you install stream-js via npm and require it in a frontend project the build will fail. This is because package.json sets the property "main" to the src entry "./src/getstream.js". We should investigate using the "browser" or "browserify" package.json property to tell build tool chains to include a distributable specifically build for the frontend. Webpack config needs to include a separate target.

getstream.js for parse has error

getstream.js for parse cloud code has error:
Result: ReferenceError: setTimeout is not defined
at nextTick (getstream.js:18709:9)
at onwrite (getstream.js:20191:7)
at WritableState.onwrite (getstream.js:20025:5)
at afterTransform (getstream.js:19806:5)
at TransformState.afterTransform (getstream.js:19781:12)
at Hash._transform (getstream.js:61:3)
at Hash.Transform._read (getstream.js:19886:10)
at Hash.Transform._write (getstream.js:19874:12)
at doWrite (getstream.js:20152:10)
at writeOrBuffer (getstream.js:20142:5)

I downloaded from:
https://raw.githubusercontent.com/GetStream/stream-js/parse/dist/js/getstream.js

Transpile to ES5

current distributable is using ES6. we should transpile to ES5 as part of the build

unconsistent do i follow filter syntax

on the js client
user1.following({limit: '10', offset: '0', feeds: ['user:42', 'user:43']})

on python client (same for php and ruby)
user_feed_1.following(offset=0, limit=2, filter=['user:42', 'user:43'])

add meaningful user agent header

USER_AGENT should be "stream-javascript-client-" + version

question: can we detect if the client is used server-side or in the browser? (eg. nodejs VS browser)

err is always null when there are server side validation errors

client.feed('notification', id).addActivity({
"actor": id2,
"actorName": "abc",
"verb": "follow"
});
body:{
"code": 5,
"detail": "Please use actorname instead of actorName for your field name",
"duration": "10ms",
"exception": "CustomFieldException",
"status_code": 400
}
err = null

Support for global callback

Often you'll want a global behaviour for loading and error handling. Currently this is not supported.

We could do something like
client.on('pre_request', callback);
client.on('response', callback);

@tbarbugli what do you think?

loading multiple results - the callback doesn't have a result argument, works differently than subscribing to a feed

Here's an example of how I get the request for the feed to work, it should come back in the argument of the callback result argument, here's how i have to get the result, this works differently than subscribing to a feed:

UserFeedCollection.prototype.subscribeToFeed = function() {
return this.me.subscribe((function(_this) {
return function(data) {
return _this.addOneAtIndex(data, 0);
};
})(this));
};

UserFeedCollection.prototype.fetch = function(lastSeenId) {
var xmHttpR;
this.lastSeenId = lastSeenId != null ? lastSeenId : 0;
if (this.lastSeenId !== 0) {
this.me.get({
limit: this.pageLimit,
mark_seen: true
});
} else {
this.me.get({
limit: this.pageLimit,
id_lt: this.lastSeenId
});
}
xmHttpR = this.me.get({
limit: 10,
mark_seen: true
});
xmHttpR.onload = (function(_this) {
return function(data) {
var item, list, _i, _len, _ref, _ref1, _results;
list = data != null ? (_ref = data.target) != null ? (_ref1 = _ref.body) != null ? _ref1.results : void 0 : void 0 : void 0;
if (!list) {
return _this.trigger('sync');
}
_results = [];
for (_i = 0, _len = list.length; _i < _len; _i++) {
item = list[_i];
console.log('item', item);
_results.push(_this.addOne(item));
}
return _results;
};
})(this);
return this.trigger('sync');
};

IE9 is not supported

both feed reads and writes are not supported. This is related to (missing) CORS support in IE9. We should at least add read support via JSONP

Bad feed slug does not set err callback argument on follow

Accidentally typed the name of my feed slug in incorrectly and did not get the behavior I expected...

var stream = require("getstream");
var client = stream.connect("REDACTED", "REDACTED");
var aggregated1 = client.feed("agggggregated", "1");
aggregated1.follow("user", "1", function(err, resp, body) {
    console.log("Err: ", err);
    console.log("Body: ", body);
});

This gives me the following output:

Err:  null
Body:  { code: 6,
  detail: 'The following feeds are not configured: \'agggggregated\'',
  duration: '13ms',
  exception: 'FeedConfigException',
  status_code: 400 }

With some different slug names, different errors can result (I tried "does-not-exist" for testing and it gave a 404 instead of 400)

I would have expected the API to return an error (via the err arguments in the callback).

I have not assessed deeper yet but I suspect other APIs have similar issues.

Faye.subscribe

Currently auth and connection are tied together. This means you cant subscribe to multiple feeds without creating multiple connections.

We should research if this can be improved and if doing so improves performance

How to get all activities?

Hello, could you help me with this problem:

  • I try to get all activities ( command: feed.get() ). When i get the response, i can't parse it ( can see it in console, but when i try to parse it in JS, the response is undefined )

Promises

Make it easy to use Stream with promises, while maintaining backward compatibility.

better test infrastructure

We clearly need to split our tests in these groups:

  • unit tests (no I/O whatsoever)
  • integration tests
  • browser tests

we should only run unit tests for regular builds. integration tests and browser tests should be run as part of the release cycle (eg. npm release_test, npm browser_test, npm integration_test).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.