GetStream-IO - Dynamic Content With Realtime data - javascript

I am trying to figure out the best approach to storing data in get-stream, and how to pull real-time data on the client-side.
For example, let's say I have a user and they have an image. When they create a post, I add an activity:
const eventStreamPromise = eventStream.addActivity({
actor: event,
verb: 'post',
object: postId,
foreign_id: postId,
postText: 'some text',
user: 'internalUserId',
});
I would think I would use just a reference to the user, which is fine for when I do an initial load on the feed (I pull the feed from the client-side). But then, I'm not sure of the best way to get this data when I subscribe to the feed on the client-side.
this.getStreamListener = feed
.subscribe((data) {
console.log(data, 'got feed data, now what?');
})
.then(() {
console.log('now listening to changes in realtime');
})
.catch((error) => {
console.log('error', error);
});
Any advice is appreciated!

The anonymous function that is passed to the subscribe() method is invoked on every realtime update. The data parameter that's passed contains the activity along with some additional metadata like the timestamp.
Within that 'callback' function you can read the fields, e.g. the 'user' id, pull data from your back-end, update your client, etc.
Hopefully that helps?

Related

How to get single value from request response

I started writing a program that will automate user actions, by now it's meant to be an easier menu to make faster actions by just sending requests to the official website by clicks on my own page. (something like web-bot but not exactly).
My problem is when i send login request in response i get back user_id, server, session_id etc. And I need to save that session_id to make the other actions.
How can i save this to variable.
All in JavaScript.
I was looking in the internet since yesterday for an answer and i still can't find (or understand) how to get this
I tried
function login(){ fetch('url', { method: 'POST', headers: { //headers }, body: //my Id's }) })
//There's the problem to solve
.then(res => res.text()) .then(data => obj = data) .then(() => console.log(obj)) console.log(body.session_id);
// I even tried the substring but 1. It won't work as I want because There are sometimes //more and less letters. 2. I get and error "Cannot read properties of undefined (reading //'substr')"
`session = obj;
session_id = session.substring(291,30)
console.log(session_id)`
It looks like you're using the text() method on the Response object returned from fetch(), which will give you a string representation of the response.
You probably want to be using the json() method instead, and from that you can get your session_id.
This guide has some more useful information that may help you: https://javascript.info/fetch
Ok it works now with
`async function login(){ let session = await fetch('url', {
//code
}
let result = await session.json();
console.log(result);
session_id = result.data.user.session_id;
user_id = result.data.user.id;`

Django and Javascript: Take Info From API And Save To Database

I'm very new to Javascript with Django and I'm looking for some basic info on how to take info from an API that has already been returned, and post it to the database. I have used views.py to take information and save it to the database, but I haven't done this with info from an API that is achieved in Javascript. My project is a weather app that gets info from OpenWeather for a city that the user types into a box, and that part works - the API information is returned. I currently have a model for each Location, I just don't know how to save it in the database.
Is this done through fetch, using POST? I am also slightly confused about how the urls would be setup. Any information, maybe some sample github code, could help :)
For example, if I want to get the location and then add it to my 'favorites' would something like this make sense? I know I would still need to make the view, and url.
const location_content = document.querySelector('#content').value;
function add_to_fav() {
fetch('/favorites', {
method: 'POST',
body: JSON.stringify({
location_content: location_content
})
})
.then(response => response.json())
.then(result => {
console.log(result);
});
localStorage.clear();
return false;
}
Here is my model for each city that is returned via the API:
class Location(models.Model):
city = models.CharField(max_length=500)

How do I set nested object entries coming from an api?

I got an object where I keep track of several things that the user can fill out, delete, update, etc.
Now, when 'loading' such a project, I make an api call to my backend using axios to retrieve the specific data to send it back to the client. The api call looks like this:
axios.get(`/api/data/${this.$route.params.dataId}`)
.then((response) => {
//Why does this not work?
this.nestedObject = response.data.object
//This DOES work... Why?
this.nestedObject.recipes = response.data.object.recipes
this.nestedObject.cheffs= response.data.object.cheffs
})
.catch((err) => {
console.log("error retrieving data: ", err);
});
Whenever I just set this.nestedObject equal to the data that is coming from the server, it does not work. nestedObject is not updated with the new values. But when I set the individual entries in the object equal to the data that is coming from the server, it does work and nestedObject is updated appropriately. Why is that?

Passing parameter to a GET request to retrieve specific information

I am trying to retrieve (GET) specific information based on a parameter that is passed. My code looks like this:
In index.js:
export var comments = (userId) => {
return new Promise((value) => {
axios.get('http://localhost:1000/getreviews/:userId')
.then((response) => {
console.log(response.data.comment);
})
})
}
In routes.js:
router.route('/:userId').get((req, res) => {
Users.find({user: req.params.userId})
.then((reviews) => res.json(reviews)
);
});
So I want to get relevant information. To give a higher-level idea of what is going on--there are multiple modals, and when a specific one is clicked I want to get specific information from the database, instead of getting all the information from the database and then do the extraction of relevant information in index.js based on the user's id. That way, I will be getting all the information on every modal click which is not efficient so I want to avoid it.
What is the problem exactly, is Users.find({user: req.params.id}) not returning the expected value? mongoose has findById which queries the db looking for the object with that specific id, in your case :
Users.findById(req.params.userId)
.then((reviews) => res.json(reviews)
);
edit: it seems like you're passing undefined as a parameter find, note that the name of the variable that is stored in params must be the same as the parameter you provided in your get method which is userId, so use req.params.userId instead.
edit2: js part
export var comments = (userId) => {
return axios.get(`http://localhost:1000/getreviews/${userId}`)
.then((response) => {
return response.data
})
}
Writing the GET request in a different way solved the issue:
axios({
method: 'get',
url: 'http://localhost:1000/getreviews/',
params: {
user: userId
})
Then I could access the userId in routes.js through req.query.user and it will give me the userId I just passed.

Converting circular structure to JSON - 3rd party API

I'm building out a project that is making a call to a blockchain API. Unfortunately, the data I'm getting back is circular so while it works in Postman my server errors when trying to convert it to JSON. I tried using JSON.stringify but nothing changed.
Here's the controller function:
blockchainController.search = (req, res) => {
axios({
method: 'GET',
url: `https://chain.api.btc.com/v3/address/${req.body.address}/tx`
})
.then(data => {
res.json({
message: 'Transactions loaded',
data: data
})
})
.catch(err => {
console.log(err);
res.send(err);
})
};
Any ideas for a workaround or a fix? I'd like to be able to send this data to my front-end but it ain't happening.
A solution could be to use a library designed to prune circular references.
I happen to have built such library: https://github.com/Canop/JSON.prune
You can simply call it with
let json = JSON.prune(yourCircularObject);
This adds some "-pruned-" marks whenever a reference is ignored.
If you prefer a "silent" removal, you can do
let json = JSON.prune(yourCircularObject, {prunedString: undefined });

Categories