Formatting data from Firebase with HTML and CSS - javascript

This time I'm facing a problem with formatting data from Firebase. This is how structure in my database looks:
I'm getting it from database using this code:
const preObject = document.getElementById('object')
var parametryObject = firebase.database()
.ref('Parametry_powietrza')
.limitToLast(1)
.once('value').then(function(snapshot) {
var listaParametrow = snapshot.val();
console.log(listaParametrow);
preObject.innerText = JSON.stringify(snapshot.val(), null, 3)
});
And on my webpage it looks like:
My question is - how to properly refer to that data to be able to change its appearance using HTML and CSS?
Thank you! :)

It looks like you're trying to access the data inside your JSON object being returned to you from your FireBase RealTime database (RTDB). But the way you've structured your data makes it near impossible for your javascript to iterate through it.
Some pointers I can give you regarding your data in the Realtime Database atm:
1) Datetime is typically stored in what's called Epoch Time. Which is typically the number of seconds since Jan 1, 1970. The number can easily be converted back into text using various javascript time libraries. An easy one to try out is Luxon. You can see epoch time with this online convertor here.
2) Secondly, RTDB supports the creation of unique, sequential, sortable "push-id" whenever you call the .push({ myDataObject }) function. So there's no need to store the date and the time as the "keys" to your object. More info about the push-id here and here. It's really interesting stuff!
3) I hate to be writing this suggestion because it seems like taking a step back before you can take steps forward, but I feel like you would benefit alot on looking at some articles on designing databases and how to sensibly structure your data. Firebase also has a great introduction here. If it's any help, for your data structure, I suggest modifying your data structure to something like below:
{
Parametry_powietrza: {
[firebase_push_id]: {
timestamp: 726354821,
Cisnienie: 1007.78,
Temperatura: 19.23,
Wilgotnosc: 52.00,
},
[firebase_push_id]: {
timestamp: 726354821,
Cisnienie: 1007.78,
Temperatura: 19.23,
Wilgotnosc: 52.00,
}
}
}
That way, when firebase returns your data, you can iterate through the data much more easily and extract the information you need like:
database
.ref('Parametry_powietrza')
.limitToLast(10)
.once('value', snapshot => {
snapshot.forEach(child => {
// do what you need to do with the data
console.log("firebase push id", child.key);
console.log("data", child.val());
})
});
All the best! BTW are you using any javascript frameworks like React or Vue?

Related

How to make a page for every single object from JSON data - JavaScript

I've JSON data
[{"name":"Zohir","id":"151232", "code":"ZO"},{"name":"Tuhhin","id":"151233", "code":"TU"}, .....]
I want to show every single object in different page & also i want to render a single student page based on "code", Like www.mylink.com/student/ZO
I don't know is my question correct or not, I'm new in JavaScript
I tried to show all data in a page from JSON file & i did that, but i can't render a single student page
function getStudent() {
fetch('https://myjesondatas123211.herokuapp.com/v/students')
.then((res) => res.json())
.then((data) => {
let output = '<h2>Students</h2>'
data.forEach(function (student) {
output += `
<div class="col-md-4">
<h4>${student.name}</h4>
<p>${student.id}</p>
<p>${student.code}</p>
</div>
`;
});
document.getElementById('output').innerHTML = output;
})
};
A solution to this problem would be fairly complex to create in plain Javascript.
You would need to have an understanding about single page applications and routers to start tackling this problem.
You might want to look over here or search for another tutorial to get the basics:
https://dev.to/rishavs/making-a-single-page-app-in-ye-good-olde-js-es6-3eng
You want to do a single-page app, which is not simple in plain javascript.
You may want to consider using frameworks for this, such as Angular or React to do this quite easily
They have native routers and allow you to create routes with parameters, and display a component depending on this parameter.

Display data from database (using mongodb) in hbs/html file Node.Js

I started studying node.js, and now I'm trying to do a "Todo-App".
I'm trying to find the best way to transfer data from my database (using mongodb) into my hbs files, so I could display it.
From the server.js -> server to the hbs -> client (correct to me if I'm wrong please, by assuming that server.js is the server of course and the hbs file is the client)
So, I succeeded to do it by passing an array.
but when I'm trying to display in html desing, it just looking bad.
The code:
app.get('/allTasks',(req,res)=>{ //get (go to) the allTasks (hbs file)
Todo.find().then((todos) => {
console.log(todos);
var arrayOfTodos = [];
todos.forEach(function(element){
console.log("\n\n\n\n\n elemnt details: ",element.text + "\n",element.completed+"\n");
arrayOfTodos.push(element.text,element.completed);
});
res.render("allTasks.hbs", {
pageTitle: "Your tasks: ",
todos: arrayOfTodos
});
});
});
The result is:
You can see a picture
As you can see, its just looking bad... cause it just display an array,
an I want to display each task seperately.
Any tips?
Thanks a lot,
Sagiv
Instead of using push just do:
Todo.find().toArray(function(err, result){
arrayOfTodos = result;
})
Once you have your array, the design got nothing to do with mongodb. You will need to learn how to use your render technology. You need to touch your html template, so you should start by posting that.
The problem solved.
I just had to learn how to handle the data in the hbs side.
so the code is: (in hbs)
{{#each todos}}
{{missionNumber}} <br>
{{text}}<br>
completed = {{completed}}<br><br>
{{/each}}
as you can see, the each is a loop , that pass on the todos parameter (my array)
and i just have to display the data in the way i want it to be displayed.
thanks for your help.

Data Formatting with Javascript to Firebase

I'm using javascript to upload data from webduino, but have trouble with the formatting part.
The part my js pushes data to Firebase is as follows:
myFirebase.push({
messages:{
time:get_time("hms"),
d
}
});
The results in Firebase look like this:
However, to make the database manageable, it has to be like this:
which the "messages" class is above all data.
Please let me know if there is anyway I can adjust my js code to achieve this, thank you!
I think this is what you're trying to do but I'm unsure:
let messagesRef = myFirebase.ref('messages')
messagesRef.push({name: 'blah', text: 'bluh'})
I've solved it,
myFirebase = new Firebase("https://watercup-e06b3.firebaseio.com/messages/");
just add the "/messages" and everything will work!

Querying a parse table and eagerly fetching Relations for matching

Currently, I have a table named Appointments- on appointments, I have a Relation of Clients.
In searching the parse documentation, I haven't found a ton of help on how to eagerly fetch all of the child collection of Clients when retrieving the Appointments. I have attempted a standard query, which looked like this:
var Appointment = Parse.Object.extend("Appointment");
var query = new Parse.Query(Appointment);
query.equalTo("User",Parse.User.current());
query.include('Rate'); // a pointer object
query.find().then(function(appointments){
let appointmentItems =[];
for(var i=0; i < appointments.length;i++){
var appt = appointments[i];
var clientRelation = appt.relation('Client');
clientRelation.query().find().then(function(clients){
appointmentItems.push(
{
objectId: appt.id,
startDate : appt.get("Start"),
endDate: appt.get("End"),
clients: clients, //should be a Parse object collection
rate : appt.get("Rate"),
type: appt.get("Type"),
notes : appt.get("Notes"),
scheduledDate: appt.get("ScheduledDate"),
confirmed:appt.get("Confirmed"),
parseAppointment:appt
}
);//add to appointmentitems
}); //query.find
}
});
This does not return a correct Clients collection-
I then switched over to attempt to do this in cloud code- as I was assuming the issue was on my side for whatever reason, I thought I'd create a function that did the same thing, only on their server to reduce the amount of network calls.
Here is what that function was defined as:
Parse.Cloud.define("GetAllAppointmentsWithClients",function(request,response){
var Appointment = Parse.Object.extend("Appointment");
var query = new Parse.Query(Appointment);
query.equalTo("User", request.user);
query.include('Rate');
query.find().then(function(appointments){
//for each appointment, get all client items
var apptItems = appointments.map(function(appointment){
var ClientRelation = appointment.get("Clients");
console.log(ClientRelation);
return {
objectId: appointment.id,
startDate : appointment.get("Start"),
endDate: appointment.get("End"),
clients: ClientRelation.query().find(),
rate : appointment.get("Rate"),
type: appointment.get("Type"),
notes : appointment.get("Notes"),
scheduledDate: appointment.get("ScheduledDate"),
confirmed:appointment.get("Confirmed"),
parseAppointment:appointment
};
});
console.log('apptItems Count is ' + apptItems.length);
response.success(apptItems);
})
});
and the resulting "Clients" returned look nothing like the actual object class:
clients: {_rejected: false, _rejectedCallbacks: [], _resolved: false, _resolvedCallbacks: []}
When I browse the data, I see the related objects just fine. The fact that Parse cannot eagerly fetch relational queries within the same call seems a bit odd coming from other data providers, but at this point I'd take the overhead of additional calls if the data was retrieved properly.
Any help would be beneficial, thank you.
Well, in your Cloud code example - ClientRelation.query().find() will return a Parse.Promise. So the output clients: {_rejected: false, _rejectedCallbacks: [], _resolved: false, _resolvedCallbacks: []} makes sense - that's what a promise looks like in console. The ClientRelation.query().find() will be an async call so your response.success(apptItems) is going to be happen before you're done anyway.
Your first example as far as I can see looks good though. What do you see as your clients response if you just output it like the following? Are you sure you're getting an array of Parse.Objects? Are you getting an empty []? (Meaning, do the objects with client relations you're querying actually have clients added?)
clientRelation.query().find().then(function(clients){
console.log(clients); // Check what you're actually getting here.
});
Also, one more helpful thing. Are you going to have more than 100 clients in any given appointment object? Parse.Relation is really meant for very large related collection of other objects. If you know that your appointments aren't going to have more than 100 (rule of thumb) related objects - a much easier way of doing this is to store your client objects in an Array within your Appointment objects.
With a Parse.Relation, you can't get around having to make that second query to get that related collection (client or cloud). But with a datatype Array you could do the following.
var query = new Parse.Query(Appointment);
query.equalTo("User", request.user);
query.include('Rate');
query.include('Clients'); // Assumes Client column is now an Array of Client Parse.Objects
query.find().then(function(appointments){
// You'll find Client Parse.Objects already nested and provided for you in the appointments.
console.log(appointments[0].get('Clients'));
});
I ended up solving this using "Promises in Series"
the final code looked something like this:
var Appointment = Parse.Object.extend("Appointment");
var query = new Parse.Query(Appointment);
query.equalTo("User",Parse.User.current());
query.include('Rate');
var appointmentItems = [];
query.find().then(function(appointments){
var promise = Parse.Promise.as();
_.each(appointments,function(appointment){
promise = promise.then(function(){
var clientRelation = appointment.relation('Clients');
return clientRelation.query().find().then(function(clients){
appointmentItems.push(
{
//...object details
}
);
})
});
});
return promise;
}).then(function(result){
// return/use appointmentItems with the sub-collection of clients that were fetched within the subquery.
});
You can apparently do this in parallel, but that was really not needed for me, as the query I'm using seems to return instantaniously. I got rid of the cloud code- as it didnt seem to provide any performance boost. I will say, the fact that you cannot debug cloud code seems truly limiting and I wasted a bit of time waiting for console.log statements to show themselves on the log of the cloud code panel- overall the Parse.Promise object was the key to getting this to work properly.

Transforming JSON in a node stream with a map or template

I'm relatively new to Javascript and Node and I like to learn by doing, but my lack of awareness of Javascript design patterns makes me wary of trying to reinvent the wheel, I'd like to know from the community if what I want to do is already present in some form or another, I'm not looking for specific code for the example below, just a nudge in the right direction and what I should be searching for.
I basically want to create my own private IFTTT/Zapier for plugging data from one API to another.
I'm using the node module request to GET data from one API and then POST to another.
request supports streaming to do neat things like this:
request.get('http://example.com/api')
.pipe(request.put('http://example.com/api2'));
In between those two requests, I'd like to pipe the JSON through a transform, cherry picking the key/value pairs that I need and changing the keys to what the destination API is expecting.
request.get('http://example.com/api')
.pipe(apiToApi2Map)
.pipe(request.put('http://example.com/api2'));
Here's a JSON sample from the source API: http://pastebin.com/iKYTJCYk
And this is what I'd like to send forward: http://pastebin.com/133RhSJT
The transformed JSON in this case takes the keys from the value of each objects "attribute" key and the value from each objects "value" key.
So my questions:
Is there a framework, library or module that will make the transform step easier?
Is streaming the way I should be approaching this? It seems like an elegant way to do it, as I've created some Javascript wrapper functions with request to easily access API methods, I just need to figure out the middle step.
Would it be possible to create "templates" or "maps" for these transforms? Say I want to change the source or destination API, it would be nice to create a new file that maps the source to destination key/values required.
Hope the community can help and I'm open to any and all suggestions! :)
This is an Open Source project I'm working on, so if anyone would like to get involved, just get in touch.
Yes you're definitely on the right track. There are two stream libs I would point you towards, through which makes it easier to define your own streams, and JSONStream which helps to convert a binary stream (like what you get from request.get) into a stream of parsed JSON documents. Here's an example using both of those to get you started:
var through = require('through');
var request = require('request');
var JSONStream = require('JSONStream');
var _ = require('underscore');
// Our function(doc) here will get called to handle each
// incoming document int he attributes array of the JSON stream
var transformer = through(function(doc) {
var steps = _.findWhere(doc.items, {
label: "Steps"
});
var activeMinutes = _.findWhere(doc.items, {
label: "Active minutes"
});
var stepsGoal = _.findWhere(doc.items, {
label: "Steps goal"
});
// Push the transformed document into the outgoing stream
this.queue({
steps: steps.value,
activeMinutes: activeMinutes.value,
stepsGoal: stepsGoal.value
});
});
request
.get('http://example.com/api')
// The attributes.* here will split the JSON stream into chunks
// where each chunk is an element of the array
.pipe(JSONStream.parse('attributes.*'))
.pipe(transformer)
.pipe(request.put('http://example.com/api2'));
As Andrew pointed out there's through or event-stream, however I made something even easier to use, scramjet. It works the same way as through, but it's API is nearly identical to Arrays, so you can use map and filter methods easily.
The code for your example would be:
DataStream
.pipeline(
request.get('http://example.com/api'),
JSONStream.parse('attributes.items.*')
)
.filter((item) => item.attibute) // filter out ones without attribute
.reduce((acc, item) => {
acc[item.attribute] = item.value;
return acc;
.then((result) => request.put('http://example.com/api2', result))
;
I guess this is a little easier to use - however in this example you do accumulate the data into an object - so if the JSON's are actually much longer than this, you may want to turn it back into a JSONStream again.

Categories

Resources