Google Apps Script - Retrieving username - javascript

This will hopefully be an easy one for you experienced developers. I'm trying to use the Google Apps Script service to get the username of the logged in user for my Google Site. I can get the email to display fine, however when I try to use the substring method to shorten to the username I get the follow error.
TypeError: Cannot find function substring in object email#email.com. (line 4, file "getusername")
I understand why I'm getting this error but not sure how to fix it. Below is my code
function doGet() {
var userEmail = Session.getEffectiveUser();
var username = userEmail.substring(0, userEmail.indexOf("#"));
var HTMLString= "<body> <h2> Logged in as " + userEmail +",</h2></body>";
HTMLOutput = HtmlService.createHtmlOutput(HTMLString);
return HTMLOutput
}
I'm guessing that because the variable userEmail is dynamic depending on the logged in user, the variable username is unable to see the email address until it has executed ?
Any help would be greatly appreciated.
Complete Javascript newbie here.
Thanks
Jack

Change:
var userEmail = Session.getEffectiveUser();
to:
var userEmail = Session.getEffectiveUser().getEmail();
If you look at the documentation for Session.getEffectiveUser(), you'll see what the "return" is. I never paid much attention to that for a long time. But, you need to always know what is returned. Some return types are: string, or an object, or an integer, or a Class. Depending upon what is returned, that will determine what you can further do. Lots of beginners notice that there is a period in between things, and are able to figure out that they need to patch things together with a period. But they don't really know what that period is for. That period is called a dot operator, and every place there is a "dot operator" is basically another step in a process. You're "chaining" multiple operations together. In the code: Session.getEffectiveUser().getEmail() there are two periods (dot operators) and two separate things happening, each with a different returned value. The getEmail() method returns a string. The documentation states that getEffectiveUser() returns a "User" But if you go to the documentation for "User" you'll see it described as a "Class". To understand what a "Class" is, you'll need to do some research.

Related

Check if inputted value is associated with another in its row from a database

I have a problem that I am not sure where to start with. Basically I have a login page and because there will be multiple users logging in, I thought that I might use my database to validate their logins:
A. Check if their usernames are in my (pre-created) database.
B. Check if the inputted username and inputted password match to the same person (in the same row.)
I am aware this is definitely not the safest way to do this, but it is for a school project, so who cares :)
I am using JS, jQuery, SQL and as little PHP as possible.
To connect and manipulate my database I am using the syntax that goes along with:
Not sure what this is called, whether it is a language, or just part of JS.
db.transaction(function(tx) {
etc.
}
where db is opening the conn. to the database.
Found it:
Using the WHERE operator combined with the AND operator to select multiple. End code looks like this:
let uname = document.getElementById("username").value;
let pword = document.getElementById("password").value;
db.transaction(function(lx) {
lx.executeSql('SELECT * FROM Users WHERE username = (?) AND password = (?)', [uname, pword]);
//Runs code if above statement returns true
});
My next question is how I would output this? How do i tell the user yay or nay?

DiscordJS: Check if input is in a string

Hello!
I will try to do my best as possible to explain this issue i have.
A bin with some of the code mentioned, with comments:
Codebin
I am currently working on a Discord bot, where there is data stored in a .json file (As string).
Maybe this should be converted to an array instead?
A user writes a command and the bot initializes a sequence where it will go through several options depending on whats found in the string.
I've been struggling with this far too long (atleast 10 hours now & i am severely out of ideas now) on getting a check in for user response, to see if the input he does is in the array.
If i write !color 76561197458345 - it starts the process as seen below:
As you see the Available Options for found Dino (Carnotaurus) is:
[Utah1, Utah2]
Which is correct since its listed as the detailcrest options for Carnotaurus below in my json
[
{
"name": "Acrocanthosaurus",
"detailcrest": "[Utah1, Utah2]",
"underbelly": "[Utah3, Utah4]",
"body1": "[Utah5, Utah6]",
"body2": "[Utah7, Utah8]",
"body3": "[Utah9, Utah10]"
},
{
"name": "Carnotaurus",
"detailcrest": "[Utah1, Utah2]",
"underbelly": "[Utah3, Utah4]",
"body1": "[Utah5, Utah6]",
"body2": "[Utah7, Utah8]",
"body3": "[Utah9, Utah10]"
}
]
What then happens is that the user is gonna give a input based on the options found (This case Utah1, Utah2).
I want the bot to check the response from user in chat, if his answer is existing in the json file.
If respond to the bot in chat with Utah1 - it would proceed to next question (Because it exists).
If respond to the bot in chat with Pizza2 - it would respond (Not found, please select available options)
TL;DR:
I simply need a way to check if user response (word) is existing in the string
If Yes: continue, If No: error
I hope someone can give tips, or atleast push in the right direction on how to procceed with this.
I found a simple, but obviously not the most smart answer to my own solution - however it works as expected.
I've changed my .json strings to simply not include any brackets
"detailcrest": "Utah1, Utah2",
To search through my string i applied a .split() function (to seperate words with ,)
const inputCheck = color.detailcrest.toLowerCase().split(',').includes(detailcrest);
If i then do a if else statement on it, it returns true or false - for the given input, if it exists in the json file.
if (inputCheck === true) {
console.log("found")
} else {
console.log("False")
}
Obviously this wouldn't be the smartest way to proceed in a professional
But in my little bot it should work out with what is expected.
Due to limits, i will accept my own answer as solution in two days.

Anyway to know it is stored in savedsearch or not

I'd like to search using savedsearch.
Here my code snippet goes.
var searchresults = nlapiSearchRecord('item', search_id, null, null);
search_id is defined as parameter in text field.
This is suitelet script so if you couldn't find similar search_id in savedsearch then it throws exception.
To avoid this I'd like to check if there is any similar internal id in saved searches.
For instance if there are two saved searches which ids are customsearch1, customsearch2.
If search_id is 'cust' then it throws exception and script finished with error.
It shows this in script log
'That search or mass update does not exist.'
Looking forward to hearing from you soon.
Regard
You can do a saved search of saved searches. You could take the results and use regex to determine if there is a similiar one. Use trim plus regex.
You could prevent this by changing your search_id parameter to a List/Record of Saved Searches.
Any reason why it has to be a text field?

protractor not clearing contents of input field

when my page loads up it has a lot of fields containing information about customers (written by somebody else). in the first name field 'Jerry' appears. I want protractor to remove this and then write my name in and expect it to be there. so far i have got this:
var firstName = element(by.css('#cust04'));
firstName.clear();
firstName.sendKeys('John');
expect(firstName.getAttribute("value")).toEqual("Johns");
at the moment it says Expected JerryJohn to equal Johns. any idea why it wont work? p.s. i am aware it is to equal Johns not John at the moment.
are you trying this on protractor 2.0 because I got a similar issue and the resolve for this issue was below. I do not know why it worked for me but it did.
var firstName = element(by.css('#cust04'));
firstName.click().clear().sendKeys('John');
expect(firstName.getAttribute("value")).toEqual("John");
if you have issues with the expect happening before the text gets entered then you can do this before the expect. I've only had a few instances where I've had to do the extra wait before the expect.
var usernameHasText = EC.textToBePresentInElementValue(firstName, 'John');
browser.wait(usernameHasText, 5000, "Failed to type in the username");
Try this code:
firstName.clear().then(function(){
var firstName = $('#cust04');
firstName.sendKeys('John');
expect(firstName.getAttribute("value")).toEqual("John");
});
clear() - returns promise, so you need to resolve it.
And in addition you assert wrong value(for the lastName) in your code.
Also I would recommend you use:
browser.ignoreSynchronization = false;
flag, in this case you do wont need to use .then block here, because protractor in this case will wait until promise will be resolved.

MongoDB determine if a record would pass findOne

I would like to find out how to do the below, without actually doing the DB Query.. i.e. I would like to know if "someData" would pass "whereClause" without putting it in a table and asking for it back again. I.e. Run the logic inside findOne without the overhead of insert and select. Just to make it more fun, please consider that I need to have it thread safe, thats why im messing with a Guid kinda thing below.. Also please note the where clause is probably gonna be more complex than the below, like { a : { $ne : 1 } }
Given Source:
someData = { a: 1, b: 2 };
whereClause = { b: 2 };
My code that needs fixing:
someData.GUID = ObjectId();
// DB QUERY - insert
db.workspace.insert(someData);
whereClause.GUID = inputsValues.GUID;
// Check if the data passes the whereClause
// DB QUERY - findOne
var whereResult = db.workspace.findOne(whereClause);
// DB QUERY - remove
db.workspace.remove({ "GUID": whereClause.GUID });
if (whereResult == null)
alert("Fail");
else
alert("Pass");
In SQL what I want can be expressed kinda like this: (pseudo syntax)
if (
Select Count(*) from ((Select 1 as A, 2 as B) Data where B = 2) Result
) = 1 then 'pass' else 'fail'
The above query never actually touches a table - that is my main goal.
Ok so I took this question to MongoDB support (10gen) and asked them for advice. It seems there is no syntactic way of saying what I want to say. Their suggestion is to use a separate mongodb instance as close to the application as possible, and to use that for only this purpose avoiding any potential slowing down due to locking etc.
So the solution is: Make a new MongoDB instance local to the app, and run thses queries in there. That would be the only way to do this.
I'll leave the question open to anyone that can provide a better solution.
Ok, so Stennie (in a comment) above has provided clues to what I think is the best answer for this situation.
He provided the link below:
what Javascript library can evaluate MongoDB-like query predicates against an object?
This has led me to 2 javascript libraries:
1) Mingo - https://github.com/kofrasa/mingo
2) Sift - https://github.com/crcn/sift.js
Mingo has the advantage of being able to evaluate MongoDB syntax, where Sift seems to be more complete. For my situation Mingo is perfect and exactly what I was looking for.
(I don't know how to give Stennie credit for this answer, but it really belongs to him)

Categories

Resources