Assign data from websocket to variables [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm getting data from a website via a websocket stream, I can see it clearly as a Json object in the console, and now I would like to display it in my frontend but I'm not sure how to do it. I tried assigning the data to a variable but I struggle a little bit to dot so. Is that even the solution ?
my code that fetches the data goes as follow :
const ws = new WebSocket('wss://ws-feed.pro.coinbase.com');
ws.onopen = function () {
ws.send(JSON.stringify({
"type": "subscribe",
"product_ids": [
"BTC-USD",
],
"channels": [
"level2"
]
}));
};
ws.onmessage = function (message) {
const msg = JSON.parse(message.data);
console.log(msg)
}
Even if I manage to display it in my app, it would appear as a whole and I would like to split each key/value pair of the object into different variables to style it properly, how can I do that ?
Thank you very much

you need to store the data inside a variable and update the ui
by changing the innerText field of an html element <div id="app"></div>:
const ws = new WebSocket("wss://ws-feed.pro.coinbase.com");
ws.onopen = function () {
ws.send(
// changed the request a bit because my pc could not handle
// the amount of the messages (1 per 0.1ms)
JSON.stringify({
type: "subscribe",
channels: [{ name: "status" }]
})
);
};
// used for a conditional rendering.
let isFirst = false;
ws.onmessage = function (message) {
/**
* destruct currencies value from the data.
* same as:
* const currencies = message.data.currencies
*/
const { currencies } = JSON.parse(message.data);
/**
* get the name of the first or second object in the currencies array.
*/
if (currencies && currencies.length > 0) {
const index = isFirst ? 0 : 1;
const name = currencies[index].name;
// update is first
isFirst = !isFirst;
/**
* find the html element you want to update.
* update the UI.
*/
document.getElementById("app").innerHTML = `
<h1>First coin on the list is <span>${name}</span></h1>
`;
}
};

Related

I want to call a single document from my Angular Firestore [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I'm facing a problem in my project, I'm using Nested Children Routing to show data in my project, I want the data of this specific item to be shown once I click the button on it, I did the routing right, it's just I can't get the proper function for the items.
Here's my service
PostsService.service.ts
getPostById(id: string){
let docId = this.afs.collection('posts').doc(id).get()
.subscribe( doc => {
if(doc.exists){
console.log('Document Id => ', doc.id)
console.log('Document data => ', doc.data())
}else {
console.log('Document not found')
}
});
return docId;
}
and Here's my TS function for the single item
.component.ts
posts: Posts[] = [];
post!:any;
constructor(
private PostsService: PostsService,
private route: ActivatedRoute
) {}
ngOnInit(): void {
let id = this.route.snapshot.params['id']
this.PostsService.getPostById(id);
}
You're attempting the get the whole collection with getPostById() and then trying to find a single document from the results. Getting the whole colletion means you will read n amount of times for n amount of documents - which is wasteful and slow.
If you ask something with getPostById() then you should do something with the return as well. Right now your asking, but not doing anything with the return.
How about we just get the single document? It will return an Observable, so we can keep monitoring the document, or just use the face value as it is.
getPostById(id: string) {
const itemDoc = this.afs.doc<any>('posts/' + id);
return itemDoc.valueChanges();
}
And in your component, don't forget to unsubscribe from the Observable.
ngOnInit() {
let id = this.route.snapshot.params['id'];
this.PostsService.getPostById(id).subscribe(post => {
console.log(post);
})
}

Firebase Functions with Realtime DB update child of child [duplicate]

This question already has answers here:
Firebase Query Double Nested
(3 answers)
Closed 10 months ago.
I have a child that get created inside my RTDB in firebase. This happens by a webservice that sends this data to firebase via the Rest API. It happens every 10 min. The data arrives and the function picks it up when it occurs. The node hold a couple of values but specifically a device: "3523EB" value that's needed for the next part. Below is the structure of that node data:
The 'device' value here "3523EB" need to update a different table that it needs to go look for with and equalTo in the devices table. Problem is the devices table has the userID and the key. So its 2 un-known values that it needs to search through as the chils its looking for contains imei:"3523EB" and it's only that child that needs to be updated.
I've tried using ref.orderByChild("imei").equalTo(deviceRef).on("child_added", function(snapshot) {
So device:"3523EB" in sigfox table has to look for and update only the child with this in is data as imei:"3523EB" in the devices table, but the {UserId} and the {key} where the table resides in devices is unknow.
Getting the values from sigfox in the function as it hits the DB is no issue: to take the value and look for the child in devices then update that child proves to be a challenge.
exports.UpdateDeviceData = functions.database.ref('sigfox/{key}/')
.onCreate((snapshot, context) => {
const deviceRef = snapshot.val()['device'];
const batteryRef = snapshot.val()['battery'];
const speedRef = snapshot.val()['speed'];
const temperatureRef = snapshot.val()['temperature'];
const latitudeRef = snapshot.val()['latitude'];
const longitudeRef = snapshot.val()['longitude'];
const timeRef = snapshot.val()['time'];
const now = new Date().getTime();
functions.logger.log('Sigfox Data Updated for device: ', deviceRef);
var db = admin.database();
var refi = db.ref("devices/");
refi.once("value", function(snapshot) {
snapshot.forEach(function(child) {
var key = child.key;
snapshot.ref.update({
battery: batteryRef,
speed: speedRef,
temperature: temperatureRef,
lati: latitudeRef,
longi: longitudeRef,
updateTime: timeRef })
functions.logger.log('Device Key Details: ',child.val());
})
});
return null;
});
Please help...
Restuctured and it works perfectly fine now:
var db = admin.database();
var query = db.ref('devices/' + deviceRef).orderByChild("imei").equalTo(deviceRef);
query.on("child_added", function (snapshot) {
snapshot.ref.update({
battery: batteryRef,
speed: speedRef,
temperature: temperatureRef,
lati: latitudeRef,
longi: longitudeRef,
updated: now})
});
thanks to: Frank van Puffelen

null value for firestore [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So basically, I can't display the collection on my html. I get a null value error for gamesList. But when I log it to the console, I can see the contents just fine, no problems there.
// get data
db.collection('games').get().then(snapshot => {
setupGames(snapshot.docs);
});
// DOM elements
const gamesList = document.querySelector('.games');
// setup games
const setupGames = (data) => {
let html = '';
data.forEach(doc => {
const game = doc.data();
const li = `
<li>
<div class="collapsible-header grey lighten-4">${game.title}</div>
<div class="collapsible-body white">${game.content}</div>
`;
html += li
});
gamesList.innerHTML = html;
}
So here something goes wrong and for the life of me I can't figure it out.
but when I use this the data does display correctly in the console, title and content:
// setup guides
const setupGames = (data) => {
let html = '';
data.forEach(doc => {
const game = doc.data();
console.log(game);
});
}
I think, when you use get() function on a collection, it already returns you the document list, so you don't need to call snapshot.docs
There's an example here:
https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_collection
If you want to use real time data with snapshots, try it this way:
db.collection('games').onSnapshot(snapshot => {
setupGames(snapshot.docs);
});

Processing one object into two results returns the object first processed in both return statements no matter what [duplicate]

This question already has answers here:
How do I correctly clone a JavaScript object?
(81 answers)
Closed 2 years ago.
I am building a firebase eco-system, but I suspect it has nothing to do with that.
This is also my first question here I think so please bare with me.
So I have got one object called articleObject containing information about a product.
let articleObject = {
title: 'title of a product',
tagline: 'tagline of a product'
}
I then send the articleObject to GCP AutoML - entity extraction, split the articleObject into two and process the results twice in two different ways since one of them retains all the info I need and the other one is actually usable with Firestore noSQL database because apparently it is a piece of s- I mean it's designed to support a flat hierarchical structure with simple queries.
async function extractEntities(articleObject) {
const projectId = 'suck-it-1454';
const location = 'us-central1';
const modelId = 'TEN657473824614fake';
let content = `${articleObject.title} ${articleObject.tagline}`
console.log(content);
let simpleObject = articleObject;
let complexObject = articleObject;
const client = new PredictionServiceClient();
// Construct request
const request = {
name: client.modelPath(projectId, location, modelId),
payload: {
textSnippet: {
content: content,
mimeType: 'text/plain', // Types: 'test/plain', 'text/html'
},
},
};
const [response] = await client.predict(request);
//simple way
for (const tagPayload of response.payload) {
let entityType = tagPayload.displayName;
let entityText = tagPayload.textExtraction.textSegment.content;
let certainty = tagPayload.textExtraction.score;
let currentCertainty;
try {
currentCertainty = simpleObject[entityType][entityText]
if (currentCertainty > certainty){
continue;
} else {
simpleObject[entityType] = entityText;
}
} catch(err) {
simpleObject[entityType] = entityText;
}
}
//complex way
for (const tagPayload of response.payload) {
let entityType = tagPayload.displayName;
let entityText = tagPayload.textExtraction.textSegment.content;
let certainty = tagPayload.textExtraction.score;
console.log(`entityType: ${entityType}, entityText: ${entityText}, certainty: ${certainty}`);
complexObject[entityType] = {[entityText]:certainty};
console.log('-------------------');
console.log(complexObject[entityType]);
console.log('-------------------');
}
console.log(complexObject);
console.log(simpleObject);
await browser.close();
return [complexObject, simpleObject]
}
Okay so the complex way pertains to it giving me a complex result where the object is formatted as such:
let complexObject = {
title: 'title of a product',
tagline: 'tagline of a product',
Brand:{"brand":0.9999993},
Manufacturer:{"manufacturer":0.958499993, "possiblemanufacturer2":0.66555444}
Model:{"model":0.93719993}
}
and the simple way gives me
let simpleObject = {
title: 'title of a product',
tagline: 'tagline of a product',
Brand:"brand",
Manufacturer:"manufacturer",
Model:"model"
}
BUT - in the end the two console.log statements before the browser.close() clause gives me the same god damn object (identical). My question is why? If I reverse the order of the for loops i.e //simple way and //complex way the result is the opposite. Both the resulting objects are always the same but what changes is if it's the complex one or the simple one that is the result.
I am using node 13 and firebase emulator is using node 10 if that matters that much.
I doubt it has anything to do with firebase.
You see the same object twice in the console because both variables simpleObject and complexObject refer to the same object in memory.
let simpleObject = articleObject;
let complexObject = articleObject;
// from this point `simpleObject` and `complexObject` refer to the same object
You can fix this issue by cloning the initial articleObject using a spread operator for example:
let simpleObject = { ...articleObject };
let complexObject = { ...articleObject };
// now `simpleObject` and `complexObject` refer to separate copies of `articleObject`

Get The Value Added Or Removed To A Firestore Array In Your Google Cloud Function [duplicate]

This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 3 years ago.
My google cloud function is triggered when an update takes place on a document in my firestore database. The update would happen from a string being added/removed to an array in the database. How do I get the exact value added/removed to the database in the cloud function?
// Update event attendance
exports.updateEventAttendance = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {
const newValue = change.after.data();
const oldValue = change.before.data();
const newEvents = newValue.eventsAttended;
const oldEvents = oldValue.eventsAttended;
// We'll only update if the eventsAttended has changed.
// This is crucial to prevent infinite loops.
if (newEvents === oldEvents) return null;
const newCount = newEvents.length;
const oldCount = oldEvents.length;
var db = admin.firestore()
if (newCount > oldCount) {
// Event added
// Get event id
// GET STRING THAT WAS ADDED TO THE DATABASE AND DO SOMETHING WITH IT
} else if (oldCount > newCount) {
// Event removed
// Get event id
// GET STRING THAT WAS REMOVED FROM DATABASE AND DO SOMETHING WITH IT
}
return null;
});
Cloud Functions tells you the document state before and after the write operation within its change.before and change.after parameters. It doesn't specify what specific fields were changed within the document, so you will have to determine that yourself by comparing the relevant fields in the before and after snapshots.

Categories