How to append to an object with Google Apps Script Editor - object

This is in Google Script Editor. I've done a lot of searching but for some reason I can't find any information about a simple thing such as appending to an object.
I have an object like this:
var get_options = {
'method': 'get',
'muteHttpExceptions': true,
};
How would I go about appending to that object?
I want to add 'authorization': 'token', to that object so the object will look like this:
var get_options = {
'method': 'get',
'muteHttpExceptions': true,
'authorization': 'token',
};
Please help! Thank you in advance.

Google App Script (GAS) uses javascript platform. So whenever you have some basic coding syntax you want to look up, refer to javascript documentation
To answer your question in brief,to add key pair value to get_options you would do the following
var get_options = {
'method': 'get',
'muteHttpExceptions': true,
};
get_options.authorization = “token”
//or
get_options["authorization"] = “token”
More detailed explanation you can be found in this SO post

Related

Porting legacy ColdFusion code to Node.js - cfhttp/request.js

I am primary a Coldfusion developer, for over 10+ years but its time to make a change. I am working through porting some old Colfusion 9 code to node js and I am struggling getting connected to the 3rd party API to access data for our company.
This is the current Coldfusion code that is connecting to the external service:
<cfsavecontent variable="thiscontent">
<post>
<username>username#domain.com</username>
<password>Pa$$w0rd</password>
</post>
</cfsavecontent>
<cfhttp url="https://API.ENDPOINT" method="post" result="httpResponse" >
<cfhttpparam type="FormField" name="xml" value="#Trim(thiscontent)#" />
</cfhttp>
This code works find, and returns the expected XML object from the service. However, this what is interesting is that if I remove the 'method="post"' perameter, I get the same error I do when trying to connect with node, more on this in a second.
For node, I am using express.js to interact with the endpoint. Here is the code I am using:
reqOpts = {
url: 'http://API.ENDPOINT',
method: 'post',
headers: {
'Content-Type': 'application/xml'
},
body: '<post><username>user#domain.com</username><password>Pa44w0rd</password></post>'
}
var getNew = request(reqOpts, function(err, resp, body){
console.log(body)
}) ;
This then return the following error:
<?xml version="1.0"?>
<response><status>FAILURE</status><message>No XML string passed</message></response>
Remember when I said that removing the post parameter from cfhttp causes the same error? I cant seem to get this to work at all in node.
I have tried using request().form, request().auth etc with no success, always the same NO XML STRING PASSED error.
I would be very grateful for any assistance.
In your ColdFusion code you used a FormField named xml.
Do the same in Node.js instead of putting the XML straight in the request body:
reqOpts = {
url: 'http://API.ENDPOINT',
method: 'post',
headers: {
'Content-Type': 'application/xml'
},
form: {
xml: '<post><username>user#domain.com</username><password>Pa44w0rd</password></post>'
}
}
var getNew = request(reqOpts, function(err, resp, body) {
console.log(body)
}) ;

How to get the request parameters using get in Spark Java framework?

I'm new to sparkjava. I want to read my request params using spark java but I'm not able to find the correct syntax. please help me out. Below is my route method and the client call to it:
my client request url:
/smartapp/getDataViewModelConfig?collId=123'
Route Method:
get("smartapp/getDataViewModelConfig/:id", "application/json", (request, response)
-> {
String id = request.params(":id");
}
The 'id' field is returning null here. Any suggestions as to what went wrong here?
If you have to work with an URL like /smartapp/getDataViewModelConfig?collId=123 you have to deal with query parameters in your implementation, like the following:
get("smartapp/getDataViewModelConfig", "application/json", (request, response)->{
String id = request.queryParams("collId");
return "HI " + id;
}
If you have an URL like : http://localhost:4567/smartapp/getDataViewModelConfig/456
use the following code :
get("/smartapp/getDataViewModelConfig/:id","application/json", ((request, response) -> {
response.type("application/json")
return request.params(":id");
}), gson::toJson);

Requestjs returning original language

I'm using request.js and cheerio to capture some text of my site.
The original text is English, and I would like to capture the translated version.
Here's what I have for the request:
request.get({uri:
'http://immocostablancasofia.com/listing/villa-in-lliber-ref-p01638/?lang=nl',
'followAllRedirects': true}
It returns the English version instead of the Dutch one.
I also tried using formData, with no luck.
Add options for request:
var options = {
url: 'http://immocostablancasofia.com/listing/villa-in-lliber-ref-p01638/',
headers: {'Accept-Language': 'nl-NL'},
qs: {lang:'nl'}
};
And
request.get(options, callback);
I changed the code adding ',headers:{'Accept-Language': 'nl-NL'}' , and it works!
request.get({uri:
'http://immocostablancasofia.com/listing/villa-in-lliber-ref-p01638/?lang=nl',headers:{'Accept-Language': 'nl-NL'}
'followAllRedirects': true}

Getting 401 uploading file into a table with a service account

I am using nodejs and the REST API to interact with bigquery. I am using the google-oauth-jwt module for JWT signing.
I granted a service account write permission. So far I can list projects, list datasets, create a table and delete a table. But when it comes to upload a file via multipart POST, I ran into two problems:
gzipped json file doesn't work, I get an error saying "end boundary missing"
when I use uncompressed json file, I get a 401 unauthorized error
I don't think this is related to my machine's time being out of sync since other REST api calls worked as expected.
var url = 'https://www.googleapis.com/upload/bigquery/v2/projects/' + projectId + '/jobs';
var request = googleOauthJWT.requestWithJWT();
var jobResource = {
jobReference: {
projectId: projectId,
jobId: jobId
},
configuration: {
load: {
sourceFormat: 'NEWLINE_DELIMITED_JSON',
destinationTable: {
projectId: projectId,
datasetId: datasetId,
tableId: tableId
},
createDisposition: '',
writeDisposition: ''
}
}
};
request(
{
url: url,
method: 'POST',
jwt: jwtParams,
headers: {
'Content-Type': 'multipart/related'
},
qs: {
uploadType: 'multipart'
},
multipart: [
{
'Content-Type':'application/json; charset=UTF-8',
body: JSON.stringify(jobResource)
},
{
'Content-Type':'application/octet-stream',
body: fileBuffer.toString()
}
]
},
function(err, response, body) {
console.log(JSON.parse(body).selfLink);
}
);
Can anyone shine some light on this?
P.S. the documentation on bigquery REST api is not up to date on many things, wish the google guys can keep it updated
Update 1:
Here is the full HTTP request:
POST /upload/bigquery/v2/projects/239525534299/jobs?uploadType=multipart HTTP/1.1
content-type: multipart/related; boundary=71e00bd1-1c17-4892-8784-2facc6998699
authorization: Bearer ya29.AHES6ZRYyfSUpQz7xt-xwEgUfelmCvwi0RL3ztHDwC4vnBI
host: www.googleapis.com
content-length: 876
Connection: keep-alive
--71e00bd1-1c17-4892-8784-2facc6998699
Content-Type: application/json
{"jobReference":{"projectId":"239525534299","jobId":"test-upload-2013-08-07_2300"},"configuration":{"load":{"sourceFormat":"NEWLINE_DELIMITED_JSON","destinationTable":{"projectId":"239525534299","datasetId":"performance","tableId":"test_table"},"createDisposition":"CREATE_NEVER","writeDisposition":"WRITE_APPEND"}}}
--71e00bd1-1c17-4892-8784-2facc6998699
Content-Type: application/octet-stream
{"practiceId":2,"fanCount":5,"mvp":"Hello"}
{"practiceId":3,"fanCount":33,"mvp":"Hello"}
{"practiceId":4,"fanCount":71,"mvp":"Hello"}
{"practiceId":5,"fanCount":93,"mvp":"Hello"}
{"practiceId":6,"fanCount":92,"mvp":"Hello"}
{"practiceId":7,"fanCount":74,"mvp":"Hello"}
{"practiceId":8,"fanCount":100,"mvp":"Hello"}
{"practiceId":9,"fanCount":27,"mvp":"Hello"}
--71e00bd1-1c17-4892-8784-2facc6998699--
You are most likely sending duplicate content-type headers to the Google API.
I don't have the capability to effortlessly make a request to Google BigQuery to test, but I'd start with removing the headers property of your options object to request().
Remove this:
headers: {
'Content-Type': 'multipart/related'
},
The Node.js request module automatically detects that you have passed in a multipart array, and it adds the appropriate content-type header. If you provide your own content-type header, you most likely end up with a "duplicate" one, which does not contain the multipart boundary.
If you modify your code slightly to print out the actual headers sent:
var req = request({...}, function(..) {...});
console.log(req.headers);
You should see something like this for your original code above (I'm using the Node REPL):
> req.headers
{ 'Content-Type': 'multipart/related',
'content-type': 'multipart/related; boundary=af5ed508-5655-48e4-b43c-ae5be91b5ae9',
'content-length': 271 }
And the following if you remove the explicit headers option:
> req.headers
{ 'content-type': 'multipart/related; boundary=49d2371f-1baf-4526-b140-0d4d3f80bb75',
'content-length': 271 }
Some servers don't deal well with multiple headers having the same name. Hopefully this solves the end boundary missing error from the API!
I figured this out myself. This is one of those silly mistakes that would have you stuck for the whole day and at the end when you found the solution you would really knock on your own head.
I got the 401 by typing the selfLink URL in the browser. Of course it's not authorized.

Greasemonkey: load url using GM_xmlhttpRequest and createContextualFragment

I have the following GreaseMonkey Script:
GM_xmlhttpRequest({
method: 'GET',
url: "http://www.testurl.com",
headers: {
'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3',
},
onload: function(responseDetails) {
var tagString = responseDetails.responseText;
var range = document.createRange();
range.selectNode(document.body);
var documentFragment = range.createContextualFragment(tagString);
How do I now extract stuff from documentFragment? documentFragment.getElementById(''), document.body etc all returns undefined.
I suspect this is due to the createContextualFragment method returning a XPCNativeWrapper object, but how do I work around this to access the underlying DOM?
Thanks
Not sure if this is answered by Load and parse remote url with greasemonkey
Depending what you want to do, might be easier to include jquery..
I suspect this is due to the
createContextualFragment method
returning a XPCNativeWrapper object,
but how do I work around this to
access the underlying DOM?
This is done using wrappedJSObject:
var documentFragment = range.createContextualFragment(tagString).wrappedJSObject;

Resources