I need to reset a json file to an original state after a button is clicked. Currently, I am modeling with router, and I need help to extend my existing code.
This is a code snippet I wrote on server.js file, the one that I run "nodemon" to start the server.
var messages = [{index:0, rating:0}, {index:1, rating:0}]
app.get('/votes', (req, res) =>{
res.send( messages )
})
app.post('/votes', (req, res) =>{
votes.push(votes)
res.sendStatus(200)
})
so my initial state on file 'votes' (json format) is:
[{"index":0,"rating":0}, {"index":1, "rating":0}]
After some user actions, I'll add some data to this json file using this code:
<body>
// some logic here
<script>
$(() => {
$("#submit").click(()=>{
var message = [ { index:1, rating: $("#input").val()},
{ index:2, rating: $("#input2").val()}]
postMessage(message)
})
})
function postMessage(message) {
$.post('http://localhost:8080/votes', message)
}
</script>
</body>
and then I have the following in my json file
[{"index":0,"rating":0}, {"index":1, "rating":0}, {"index":1, "rating":1}, {"index":2, "rating":3}]
QUESTION: How do I reset the json file (not json variable) into the initial state with a button click for a new transaction?
I am just doing prototyping, so a quick and dirty way may work.
I'd recommand build or use some sort of user verification, and for each user have a copy of the initial data just for him. Keep in mind that this data will never garbage collected so you will have to manage deletion by yourself. I used basic IP that is given by express but that is not a good practice.
Use npm-memorystore which will give your some memory management.
If you want to identify users you can use express-session, express-jwt
var messages = [{
index: 0,
rating: 0
}, {
index: 1,
rating: 0
}];
var usersMessages = {};
app.get('/votes', (req, res) => {
var userIp = req.ip;
usersMessages[userIp] = [].concat(messages);
res.send(usersMessages[userIp]);
});
app.post('/votes', (req, res) => {
var userIp = req.ip;
var userVotes = usersMessages[userIp];
if (!userVotes)
usersMessages[userIp] = [].concat(messages);
usersMessages[userIp].push(req.body.votes);
res.sendStatus(200)
});
Take a look this:
$(() => {
let message = [];
$("#submit").click(() => {
//fill with values
message = [
{ index: 1, rating: $("#input").val() },
{ index: 2, rating: $("#input2").val() }
];
postMessage(message); //send post
message = []; //reset array
});
function postMessage(message) {
$.post("http://localhost:8080/votes", message);
}
});
Hope this helps. =D
What you need to do is, just remove all of the object from array.
You can do that as follow.
var messages = [{"index":0,"rating":0}, {"index":1, "rating":0}, {"index":1, "rating":1}, {"index":2, "rating":3}];
messages.length = 1;
console.log(messages);
Another way.
var messages = [{"index":0,"rating":0}, {"index":1, "rating":0}, {"index":1, "rating":1}, {"index":2, "rating":3}];
messages = messages.slice(0,1);
console.log(messages);
What above code do is, it will just set array back to it first value.
Related
I am creating an e commerce mobile app using React Native, within this I have a server, the role of the server is currently to get products from the woocommerce APi, take only the fields I need : name, id, category,price, image and then add another field called 'favourite'(for my wishlist).
Everything was worked well until the getProducts method has a method that calls the woocommerce API and then pushes that to the database. Problem is that whenever I try to update an item to 'true' rather than 'false' within the favourite field. It populates but when I refresh the page which also recalls the API, it brings the 'favourite' field back to false, which it was initially initialised as in the server.
I present the code in question:
app.get("/getProductsForUser", async (req, res) => {
const productDetails = {};
const numberOfProducts = 25;
api
.get("products", {
per_page: numberOfProducts, // 20 products per page
})
.then((response) => {
// Successful request
var key = "Products";
productDetails[key] = [];
var data;
for (let index = 0; index < numberOfProducts; index++) {
productDetails[key].push({
id: response.data[index].id,
name: response.data[index].name,
image: response.data[index].images[0].src,
price: response.data[index].price,
favourite: false,
category: response.data[index].categories[0].name,
});
}
db.collection("users")
.doc(req.query.userID)
.collection("products")
.doc("0")
.set({ productDetails });
res.send(productDetails);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error);
})
.finally(() => {
// Always executed.
});
});
If there is a way I can only call the above function once in the whole project (which is in nodejs by the way) and then after that only call from the database, that will help?
Just get your stored product in the DB before you push the product to the list: something like :
for (let index = 0; index < numberOfProducts; index++) {
const storedProduct = db.collection("products").getByID(response.data[index].id);
productDetails[key].push({
id: response.data[index].id,
name: response.data[index].name,
image: response.data[index].images[0].src,
price: response.data[index].price,
favourite: storedProduct.favourite ,
category: response.data[index].categories[0].name,
});
}
so instead of setting it always to false set it to the stored value.
You could also implement it in a different way. where you don't have to get the products every time for the woocommerce API. to provide you with such a solution I will need more context to your application. for example, do you have a way to run timely triggered scripts? or is it possible to call the woocommerce API somewhere else and store the results in the DB so you don't need to call it every time the you have a call to /getProductsForUser
I am fairly new to Coding and JavaScript altogether. I am trying to render the Data inside stored inside my MongoDB in my EJS template.
The specific code is here in app.js
// Individual Customer's page
app.get("/customers/all-customers/:customerPhoneNumber", function (req, res) {
const requestedCustomerPhoneNumber = req.params.customerPhoneNumber;
Customer.findOne({ phone: requestedCustomerPhoneNumber }, function (
err,
foundCustomer
) {
Purchase.find({ customerPhone: requestedCustomerPhoneNumber }, function (
err,
foundPurchases
) {
// console.log(foundPurchases);
foundPurchases.forEach(function (purchase) {
const planPurchaseID = purchase.purchaseID;
CompletedSession.findOne({ planPurchaseID: planPurchaseID }, function (err, foundSession) {
res.render("customer-page", {
customerPurchases: foundPurchases,
pageTitle: foundCustomer.name,
customerID: foundCustomer._id,
customerPhone: foundCustomer.phone,
customerWhatsapp: foundCustomer.whatsappNumber,
customerEmail: foundCustomer.email,
customerDOB: foundCustomer.dob,
customerGender: foundCustomer.gender,
customerRegDate: foundCustomer.registrationDate,
comletedSessions: foundSession.sessions,
});
})
})
});
});
});
In this code, Some of the document has null value of sessions in foundSession, which cause my program to crash when I try to render the array with forEach() loop.
Is there any way to automatically drop foundSession with null value of sessions so that I can only pass the foundSession that has no null value of sessions and prevent my program from crashing?
I am trying to create a customfield in jsforce and am having a heck of a time doing it. I can create a custom object fine, but when trying to make a field so the clients users to sort their leads by it is giving me a heckof a time. This is what I did to create a object
var jsforce = require('jsforce');
var conn = new jsforce.Connection();
conn.login('myemail', 'my password and token', function(err, res) {
if (err) { return console.error(err); }
var metadata = [{
fullName: 'TestObject1__c',
label: 'Test Object 1',
pluralLabel: 'Test Object 1',
nameField: {
type: 'Text',
label: 'Test Object Name'
},
deploymentStatus: 'Deployed',
sharingModel: 'ReadWrite'
}];
conn.metadata.create('CustomObject', metadata, function(err, results) {
if (err) { console.err(err); }
for (var i=0; i < results.length; i++) {
var result = results[i];
console.log('success ? : ' + result.success);
console.log('fullName : ' + result.fullName);
}
});
{
if (err) { return console.error(err); }
console.log(res);
}
})
That works fine but it is not what I need. Any help would be greatly appreciated as the client wants this out. It is part of a larger project that we have already completed but now the fields have to be dynamically created so the end users don't have to make the fields themselves in order for us to push the data to their account. We are currently pushing stuff but its under another field whose name doesn't make sense
I have been able to accomplish this by making a package in the salesforce website. All my clients users have to do is to click a simple link click install and it makes a list view and creates the fields i need.
Im actually trying to build up a complete chat with Sails.js websockets but im facing some troubles.
I succeed to send and get new messages when a new client connect to the chat but i would new client to get the older messages (like the 20 last messages sent in the chat).
Message.js (Model)
module.exports = {
attributes: {
name : { type: 'string' },
message : { type: 'string' }
}
};
MessageController.js (Controller)
module.exports = {
new: function(req, res) {
var data = {
name: req.param('name'),
message: req.param('message'),
};
Message.create(data).exec(function created(err, message){
Message.publishCreate({id: message.id, name: message.name, message: message.message});
});
},
subscribe: function(req, res) {
Message.watch(req);
}
};
I had an idea about using the "find" function on my Model but not really conclusive.
I hope im not missing something big about Sails possibilities !
Need your help :) Thanks !
Message.find({sort: 'createdAt ASC'}).exec(function(err, results) {
//results is an array of messages
});
http://sailsjs.org/documentation/concepts/models-and-orm/query-language
I added this code to my subscribe function but i don't receive anything on my client side listening on('message')
/* Get the last 5 messages */
Message.find({sort: 'createdAt DESC'}).limit(5).exec(function(err, messages) {
for (var i = 0; i < messages.length; i++) {
sails.sockets.broadcast(req.socket, 'message', messages[i]);
}
});
I'm trying to scrape from yelp and have attached the code below. I have problem in storing the data into array.
Here is my code:
...
var id, title, link, neighborhood, address, phone = [];
router.get('/', function(req, res, next) {
var cheerio = require('cheerio');
while (scrapepage) {
var options = {
uri: 'https://www.yelp.co.uk/search?find_desc='+find+'&find_loc='+city+''+'&start='+page,
transform: function (body) {
return cheerio.load(body);
}
};
page += 10;
rp(options)
.then(function ($) {
var json = { id: "", title : "", link : "", neighborhood : "", address : "", phone : ""};
$('.biz-name span').filter(function(){
var data = $(this).text();
console.log(data);
//title.push(data);
title_count++;
});
...
res.send('Check your console!')
})
.catch(function (err) {
// Crawling failed or Cheerio choked...
});
}
});
So whenever I try to push the data to array, it just does not work, keeps waiting forever. If I remove the push, it consoles all the data.
I also tried with each instead of filter, but no luck. Also tried to put manually into array index, still did not work. May I know what am I doing wrong in the code?
UPDATE
I have added this at the top of the page.
var id, title, link, neighborhood, address, phone = [];
I'd have to ask where is title initialized? I see the declaration but nothing that tells the system to initialize title as an array.
try
...
router.get('/', function(req, res, next) {
var cheerio = require('cheerio');
while (scrapepage) {
var options = {
uri: 'https://www.yelp.co.uk/search?find_desc='+find+'&find_loc='+city+''+'&start='+page,
transform: function (body) {
return cheerio.load(body);
}
};
page += 10;
rp(options)
.then(function ($) {
var title = [],
release, rating;
var json = { id: "", title : "", link : "", neighborhood : "", address : "", phone : ""};
$('.biz-name span').filter(function(){
var data = $(this).text();
console.log(data);
title.push(data);
title_count++;
});
...
res.send('Check your console!')
})
.catch(function (err) {
// Crawling failed or Cheerio choked...
});
}
});
without the initialization the system has to go through a process of determining type and compatibility of parameters to be sure it can give you as close to what you've asked for. Sometimes Explicitly defining a variable can speed this process up.
also with this you shouldn't need to use title_count as title.length would have the count of elements.
push will not work until assign title as an array type
then(function ($) {
var title=[];
var release, rating;
var json = { id: "", title : "", link : "", neighborhood : "", address : "", phone : ""};
$('.biz-name span').filter(function(){
var data = $(this).text();
console.log(data);
title.push(data);
title_count++;
});
...
res.send('Check your console!')
})