Really strange error post with google script - javascript

I'm trying to make a post with google Apps.
function makePost(url,page,status,token) {
var form = {
"page" : 1,
"statuses[]": status.toString().toLowerCase(),
}
var options = {
'method': 'post',
'headers' : {"Authorization" : "BASIC "+token},
'contentType': 'application/x-www-form-urlencoded',
'payload' : form,
};
var response = UrlFetchApp.fetch(url, options);
var jsonResponse = JSON.parse(response.getContentText());
return jsonResponse;}
The problem seems to be that page is being past as 1.0 what makes the destination url return an error when tries to cast.
Already tried the answer in How to convert a string to number using Google Apps Script .
I cant pass it as a String , because in that case the API returns the result with an strange behaviour.
Is it possible to pass this as Integer without being change it to 1.0 ?
Any suggestion or help will be helpfull,
thanks
UPDATE: So , i couldnt find a way to accomplish this. UrlFetchApp changes it every time. Lucky for me we could solve it by order the response in the API , and the behaviour passing a string stoped being erratic.
Thanks for the help and suggestions!

Same here connecting with Stripe REST which enforces a form-based body. It must be a bug of UrlFetchApp.
When I use
payload: {
amount: 1000,
currency: 'USD',
}
UrlFetchApp always encoded it into, note the decimal .0
"payload":"amount=1000.0&currency=USD"
But I resolved it by converting it to a String.
payload: {
amount: String(1000),
currency: 'USD',
}
Oddly, the payload will now be encoded correctly into
"payload":"amount=1000&currency=USD"
since the form-urlencoded doesn't specify the type of value, in this case, either a numeric String or an Integer. It's the server's implementation for interpreting the value.

Related

Does the Elasticsearch bulk API JavaScript sample code work correctly?

I want to use Elasticsearch bulk index with JavaScript, and follow the official document. Basically I just used it as is, but it throws an exception saying that the bulk request must be terminated by a newline code, which seems to be JSON lines.
My question is, if so, how can I convert the JSON to JSON lines and then pass it to bulk API? or am I missing some options when calling client.bulk?
ResponseError: illegal_argument_exception: [illegal_argument_exception] Reason: The bulk request must be terminated by a newline [\n]
at SniffingTransport.request
I use Elasticsearch v7.15 and Node.js v16.15 on macOS.
I second this. I'm using 8.2 and it doesn't work. I followed the example exactly and it still throws the newline error.
You used to be able to pass in the operation followed by the document in an array and it would work just fine but it seems to have been "updated" for the worse.
I'll keep trying and see if I come up with something.
EDIT: OK. I found something that works for me and I hope it works for you as well.
I made a child client to reuse the connection. It's pretty straight forward but here's the link: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/child.html
I modified the accept and content-type headers for that client and the code for setting up the client looks like so:
const es = require('#elastic/elasticsearch');
const es_hosts = [
'https://elastic_host1',
'https://elastic_host2'
];
const es_client = new es.Client({ node: es_hosts });
const es_bulk = es_client.child({
headers: {
'accept': 'application/json',
'content-type': 'application/json'
}
})
I'm assuming you're passing in an array which has an operation and a document. We'll convert that array into what equates to be a large string, remembering to tack on the newline.
let bulk_data = [
{ index: { _index: 'my-index' } },
{ id: 1, name: 'dave', job: 'janitor' } }
]
let bulk_body = {
body: bulk_data.map(JSON.stringify).join('\n') + '\n'
}
const results = await es_bulk.bulk(bulk_body);
Let me know if this helps.

Setting dataType JSON in aws-sdk for sqs

Im just trying to send a json object to sqs queue by using aws-sdk npm package.
const sqsMessage = {
MessageAttributes: {
"data": {
DataType: "String",
StringValue: payload.data
}
},
MessageBody: JSON.stringify(payload),
QueueUrl: queueUrl
If i pass json object in data attribute it tells it expected String, if i add Json then it also throws an error about type, does anyone know a workaround or what to use to get the json?
Some useful links i've found,
1)https://blog.chrismitchellonline.com/posts/aws-sqs-message-with-attributes/
https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-send-message.html
Would really appreciate some guidance on this
Can you share the error message that you're receiving. And can you show us an example of payload that you're constructing? Basically, the allowable values for dataType are found here: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_MessageAttributeValue.html
Specifically, this part: "Amazon SQS supports the following logical data types: String, Number, and Binary. For the Number data type, you must use StringValue."
So when it comes to constructing the value for your key MessageBody, you want to use JSON. So the type must be string and your value, it has to be valid JSON that's really a string and the inner quotes escaped. So for example, something like this:
"{\"foo\": \"bar\"}"
I ran into this same issue while writing unit tests in goLang and it works. I know this is 11 months later, but hopefully this helps you or someone else in the future :)

how to read the error of a callback function in node.js

I am writing some code in order to call an api and get some data.... the code has a github repository https://github.com/kwiksand/yobit and I an calling one of the function/method called addTrade (under index.js)...
After passing API key and security, I have the following code:
privateYoBit.addTrade(function(err,data){
console.log(data);
console.log(err)
},"eth_btc","buy",0.04, 0.02);
}
I get the following response:
{ success: 0, error: 'invalid method' }
null
My questions are:
console.log(err) return a "null value: does it means the code is ok and the problem is at the other end (the API)?
how do I debug/refine the "invalid method" return?
any help/support is much appreaciated
Regards
Reading source of the mentioned library, it looks like the author is sending along the following params as part of the request:
var params = {
symbol: symbol,
type: type,
amount = amount,
price = price
}
However, reading the documentation for the API, they expect the following 4 parameters:
pair : pair (example: ltc_btc)
type : transaction type (example: buy или sell)
rate : exchange rate for buying or selling (value: numeral)
amount : amount needed for buying or selling (value: numeral)
Maybe try adjusting the library to conform to the parameters the API expects?
If I were you, I would be really careful about using an untrusted, untested API to make trades...

Need Help to implement Tincan Javascript API

I'm working on tincan JavaScript API. The issue my data format is total change and TinCan have specified a why to pass data along with call. Help me to adjust my data in TinCan Api format. Here is sample data one of my call.
var data = {
"groupId": "groupId",
"groupName": "gNameEncrypt",
"tutorNames": "tutorNames",
"actorNames": "actorNames",
"otherNames": "otherNames"
};
Current what i do i simply decode this data and send it like this.
var actionList = new TinCan(
{
recordStores: [{
endpoint: "http://example.com",
username: username,
password: password,
allowFail: false
}]
});
var action = new TinCan.Agent({
"name": "insert"
});
actionList.getStatements({
'params': {
'agent': action,
'verb': {
'id': $.base64.encode(data)
}
},
'callback': function (err, data) {
console.info(data.more);
var urlref = "http://<?php echo $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . $uriParts[0] . "?" ?>t=" + data.more.TutorToken;
window.location.href = urlref;
}
});
crypt.finish();
});
There are really two parts here:
need to get data into an xAPI (formerly Tin Can) format, and
the code itself.
In depth,
I think you need to take another look at how xAPI is used in general. Data is stored a JSON "Statement" object that has 3 required properties and various other optional ones. These properties often contain complex objects that are very extensible. It is hard to tell from what you've shown what you are really trying to capture and what the best approach would be. I suggest reading some material about the xAPI statement format. http://experienceapi.com/statements-101/ is a good starting point, and to get at least some coverage of all the possibilities continue with http://experienceapi.com/statements/ .
The code you've listed is attempting to get already stored statements based on two parameters rather than trying to store a statement. The two parameters being "agent" and "verb". In this case We can't tell what the verb is supposed to be since we don't know what data contains, I suspect this isn't going to make sense as a verb which is intended to be the action of a statement. Having said that the fact that the "actor" has a value of action is questionable, as that really sounds more like what a "verb" should contain. Getting the statements right as part of #1 should make obvious how you would retrieve those statements. As far as storing those statements, if you're using the TinCan interface object you would need to use the sendStatement method of that object. But this interface is no longer recommended, the recommended practice is to construct a TinCan.LRS object and interact directly with it, in which case you'd be using the saveStatement method.
I would recommend looking at the "Basic Usage" section of the project home page here: http://rusticisoftware.github.io/TinCanJS/ for more specifics look at the API doc: http://rusticisoftware.github.io/TinCanJS/doc/api/latest/

How to configure dataFeed and server-side filtering for ui.suggest?

I'm following this sample to create a suggest control attached to text field:
webix.ui({
view: "suggest",
input: $$("testText"),
body:{
dataFeed:"/data.php"
}
});
The datafeed property sends the request to the server and returns the filtered data. Th request is
"data.php?filter[value]=Ar" // where 'Ar' is a typed text
But what if I need to limit the minimal number of typed symbols to send the request? For example, I want to reload the data when more than 3 characters are typed.
It possible or do I need to write my own method? How to do that?
Thanks in advance for any hint.
This seems not to be trivial, I found this solution on the webix forum :
body:{
dataFeed: function(filtervalue){
if(filtervalue.length<3) return;
var urldata = "filter[value]="+encodeURIComponent(filtervalue);
this.load("http://docs.webix.com/samples/13_form/01_controls/server/data.php?"+urldata, this.config.datatype);
}
}
Demo snippet : http://webix.com/snippet/4019c87a

Categories

Resources