My Code.gs has following function to filter data according to the username.
Sign in Function with Cache.put
function signin(obj){
...
....
**var Cache = CacheService.getScriptCache();
Cache.put('username',f[4])**
output = true
}
})
return output
}
**
Spreadsheet data as per column name**
`
function getByName(user, colName = 'userid') {
...........
Next data filter as per username (Cache.get)
`
function getFilteredData() {
**var Cache = CacheService.getScriptCache();**
var username = Cache.get('username')
var values = getByName(username)
Logger.log(username)
return values
}
I used getScriptCache as above functions
1.When I signed in from first account, I get correct filtered data
2.When I signed in from second account, I get data filtered as in First account. When I refresh and logged in to second account, I get correct filtered data as per second username. What I missed here?`
Related
I'm trying to create a custom datastudio connector that connect to WooCommerce rest API. I want to differentiate between orders placed by a registered user and orders placed by a guest user.
The WooCommerce API gives me the custumer_id field, if the customer_id = 0, the order was placed by a guest, otherwise the user is registered.
I followed the google data studio tutorial : https://developers.google.com/datastudio/connector/get-started
And this is my responseToRow function:
/**
Parse the response data given the required fields of the config
#return the parsed data
*/
function responseToRows(requestedFields, response) {
// Transform parsed data and filter for requested fields
return response.map(function(dailyDownload) {
var row = [];
requestedFields.asArray().forEach(function (field) {
switch (field.getId()) {
case 'id_order':
return row.push(dailyDownload.id);
case 'total':
return row.push(dailyDownload.total);
case 'date_created':
return row.push(dailyDownload.date_created);
case 'registered_user' :
if(parseInt(dailyDownload.customer_id) > 0)
return row.push(dailyDownload.customer_id);
case 'guest_user' :
if(parseInt(dailyDownload.customer_id) == 0)
return row.push(dailyDownload.customer_id);
default:
return row.push('');
}
});
return { values: row };
});
}
The function is similar to the one given in the tutorial, the others fields works fine. I'm just returning when the customer_id is different of 0. It seem to work, but I get null values when the condition doesn't hold.
I would like to remove the null values, having only the orders when the customer_id was 0 on the right and the same for the complement on the left part.
Thanks for the help
I would try it like that after filling the row array:
row.forEach((element, index) => {
if(element.guest_user == null){
// To remove the row-entry with guest_user==null
row[index].slice();
}
})
And if you don't want to remove the entries from the array just create a new array and use newArray.push(element); to copy the null ones into it.
I have stored some unique codes in MySQL as array in respective to user email, now i want to verify the user with email and unique code submit by user. I want to create a query where i can match email and unique id stored in database, to proceed the user.
Database Entry:
["BZFeWwnmr8Rm6tuu","daFJWZCEtp2WzxtD","VV80UQQZ1ym77h0m"]
I have tried FIND_IN_SET
This is the code for API, I have stringify the user entered data, where it returns the value if there is single unique value stored, But if i fetch array of unique code e.g, ["BZFeWwnmr8Rm6tuu","daFJWZCEtp2WzxtD","VV80UQQZ1ym77h0m"]
the MySQL query not working.
exports.vr_client_detail = function (req, res) {
const JSON_DATA = 'application/json';
if(req.headers['content-type'] === JSON_DATA){
if (req.body) {
var unique_string = JSON.stringify(req.body.unique_string);
var email = req.body.management_email;
db.sequelize.query('SELECT * FROM im_vr_client_activation '+
'WHERE FIND_IN_SET(unique_string, '+"'"+unique_string+"') AND "+
' management_email= ' + "'" + email + "'").then(function(app){
var arr = app[0];
return res.json({response_status:'success', response_code:185, data:arr, response:'Successfully fetch data.'})
});
}else{
return res.json({response_status:'error',response_code:10001,response:'Post data is empty.'});
}
}else{
return res.json({response_status:'error',response_code:10000,response:'Post data is not a json type.'});
}
}
The data returns nothing
{
"response_status": "success",
"response_code": 185,
"data": [],
"response": "Successfully fetch data."
}
It would be best if you normalized your schema, using a many-to-one table to hold all the unique strings instead of putting them into a single column.
But if you can't do that, you need to remove the [ and ] characters so you can use FIND_IN_SET().
You should also use a parametrized query to prevent SQL injection. See How to create prepared statements in Sequelize?
db.sequelize.query('SELECT * FROM im_vr_client_activation '+
'WHERE FIND_IN_SET(:unique_string, SUBSTR(unique_string, 2, LENGTH(unique_string)-2)) ' +
'AND management_email = :email', {
replacements: { unique_string: unique_string, email: email }
}).then(...)
If you're using MySQL 5.7 or higher you can change the datatype of the column to JSON and use JSON_CONTAINS(). And in 8.0 you can use the MEMBER OF operator.
Situation
I have firebase database that looks like this:
But i want to add a balance json object and calculate the sum of amount on every write to the database.
And it should look something like this:
Now, i am using firebase cloud functions for this purpose. I want to read txn.amount from "/Txns/{Id}" and do balance=balance+txn.amount on every write operation in the database.
This is my index.js file from firebase cloud functions
exports.addToBalance = functions.database.ref('/Txns/{pushId}')
.onWrite(event => {
const rootRef = event.ref.root
var currentBalance // variable to store the current balance got from promise
const txn = event.data.val() // getting the data from onwrite
console.log("got the balance reference :" + balanceRef)
rootRef.balance = 0.00 // set balance to zero
const setBalanceZeroPromise = ...... ? // how to get reference to balance & set the value to 0
return setBalanceZeroPromise.then(event => {
console.log("balance set to zero")
})
})
Please help !
I'm using Passport, Nodemailer, Sequelize, and Express to handle verification of user accounts who have signed up via email to the app.
To test this feature, I use Mailinator accounts to sign up, and send the email (along with a query string containing the user email and a uniquely-determined verification code) to the specified Mailinator address using Nodemailer. I then open the email in Nodemailer, click on the verification link, which updates the verification flag in the database and verifies the user.
This process works as I expect it to for exactly one user who signs up via email. When a second user signs up, the verification email is sent just as before with the username and unique verification codes in the query string, but this time, multiple users are being returned from the User.findAll query through Sequelize when the link is clicked. My query is intended to findAll possible matches of both email addresses and verification codes (since each user can only sign on with one email address and verification codes are unique), but for some reason the query is returning all matches from that query.
Here is some code for reference:
/* Sending the emails */
emails.sendActivationEmail = function(user){
const qso = {username: user.username, activationCode: user.activationCode};
const qs = querystring.stringify(qso);
const from = new helper.Email(<myEmailAddress#email.com>);
const to = new helper.Email(user.username);
const subject = 'Welcome to My Site!';
const content = new helper.Content('text/html', "<p> Thanks for signing up " +
"for our psych study, please <a href=\"http://localhost:7000/users/validate/account?" +
qs + "\">confirm your email</a></p>");
const mail = new helper.Mail(from, subject, to, content);
sendMail(mail); //invokes SendGrid mail helper function
}
/* Function invoked when user clicks on verification link in email */
emails.validateUserAccount = function(req, res){
const url = parseUrl(req.url);
const query = querystring.parse(url.query);
db.User.findAll({where: query}).then(function(matches){
if(matches.length !== 1){
res.send('error: multiple users found');
}
else{
db.User.update({
isVerified : true
},
{
where: {
username: matches[0].username
}
});
req.session.user = matches[0];
res.redirect('/');
}
}).catch(function(err){
console.error(err);
res.send(err);
});
}
Console statements in the validateUserAccount() function reveal that the query is exactly as I expect ({username: <emailAddress>, activationCode: <uniqueCode>}). However, console.log statements made in the first line after the findAll query is executed reveal that all users are being returned from the query, which should be impossible if the WHERE query is being passed in correctly, which it looks like it is from the logged statements. Why is User.findAll returning incorrect results from my query?
The problem here is that you are using the return value of querystring.parse()
As denoted in the Node docs:
Note: The object returned by the querystring.parse() method does not prototypically extend from the JavaScript Object. This means that the typical Object methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work.
It's likely the where clause expects an actual JS Object.
Further, as #doublesharp mentioned, you probably want to be fetching one row and validating it, as opposed to findAlling the rows and then filtering through. Also, you should take advantage of callbacks. You're writing blocking code right now.
I am trying to insert a document id into the user.profile key when in Accounts.onCreateUser(), as to be able to associate a separate document in a different collection (holding user information) to a user when they are signed in.
//serverMain.js
Accounts.onCreateUser(function(options,user){
var userId = user._id;
user.profile = user.profile || {};
_.extend(user.profile, {profComp: false});
insertShopObject(userId);
return user;
});
The insert I am using is
insertShopObject(userId);
This inserts a new document with pre-set fields into a separate collection called ‘ShopList’, I have passed in the userId as a parameter which is added as a field into the ‘ShopList’ collection. I can see from the server console that the document _id is returned when I call insertShopObject(userId);
I somehow want to catch that id when the document is inserted and add it into the user.profile key on user creation like so
_.extend(user.profile,{shopId: <-- ?-->})
Here is the insertShopObject function, I have tried returning instead of console logging the ‘result’ into a holding variable with no luck.
//serverMain.js
insertShopObject = function(userId){
var newShop = {
//pre-set fields.....
}
ShopList.insert(newShop, function(error,result){
if(error){console.log(error);}
else {console.log(result)}
});
}
You need to make the insert synchronous for this to work. Omit the callback from ShopList.insert() and do:
insertShopObject = function(userId){
var newShop = {
//pre-set fields.....
}
var shopId = ShopList.insert(newShop);
return shopId;
}