Google Apps Script - Woocommerce Integration payload [duplicate] - arrays

running into problems between GAS and WC RESTv2, Im trying to create a simple product with custom attributes, while I am able to do so without any specific parameter the REST api return this error:
ERROR:
{"code":"rest_invalid_param","message":"Invalid parameter(s): attributes","data":{"status":400,"params":{"attributes":"attributes[0] is not of type object."},"details":{"attributes":{"code":"rest_invalid_type","message":"attributes[0] is not of type object.","data":{"param":"attributes[0]"}}}}}
// the product gets CREATED fine using this simple var data structure :
var data =
{
"name" : " TESTING HERE TOO",
//"sku" : "TESTINGINGING ",
"type" : "simple",
"regular_price" : "1.99",
"weight" : 10,
"manage_stock" : true,
"stock_quantity" : 10,
"description" : "testing \n" } ;
var surl = website + "/wp-json/wc/v2/products?consumer_key=" + keys + "&consumer_secret=" + scret;
var options =
{
"method": "POST",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
"payload": data
};
``` // -- the product DOES NOT get created using this :
var data =
{
"name" : " TESTING HERE TOO",
//"sku" : "TESTINGINGING ",
"type" : "simple",
"regular_price" : "1.99",
"weight" : 10,
"manage_stock" : true,
"stock_quantity" : 10,
"description" : "testing \n" } ;
"attributes" : [ { "variation" : "false", "options" : "[ANY]", "id" : 0.0, "name" : "Supplier", "position" : 0.0, "visible" :"false"} , { "variation" : "false", "options" : "[ANY]", "id" : 0.0, "name" : "Invoice", "position" :1.0, "visible" :"false"}]
Any body could shed some light where could be the issue?

In case anybody stumble here, here´s the solution:
if you´d like to know where´s the bug, here it is
var options =
{
"method": "POST",
//"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", -- it does NOT WORK like content type must be JSON
"contentType": "application/json",
"muteHttpExceptions": true,
"payload": JSON.stringify(data2) -- as long as JSON payload thus stringify accord.
//"payload": data2
};
when you have a JSON within an array in GAS, the only way REST api calls will understand is if you modify 2 things
"contentType": "application/json",
send the payload to rest api WC as json
"payload": JSON.stringify(data2)
trans for the javascript object into json so WC rest api can understand
done.

Related

Laravel Input array of objects to api routes

I'm passing the following request to laravel api, but when I dump the input request, Laravel is returning an empty array.
{
"expense_type" : "payment",
"description" : "test",
"notes" : "My notes",
"expense_date": "2019-01-15",
"cost" : 100.50,
"group_id" : 1,
"shares" : [
{
"user_id" : 1,
"paid_share" : 100.50,
"owed_share" : 00.00
},
{
"user_id" : 2,
"paid_share" : 00.00,
"owed_share" : 50.25
},
{
"user_id" : 3,
"paid_share" : 00.00,
"owed_share" : 50.25
}
]
}
The output when dumping the input $request->all() is []
can some one help if there is something wrong in the request
When you send data in request as json data then $request->all() will always return empty. In order to access data in $request->all() variable you have to send form data not json data.
So, when json data is sent through api, you can access it as array in the controller like this:
$data = json_decode(file_get_contents("php://input"), true);
Now, you can access the values like $data['expense_type']
I hope you understand.

How to retrieve data from mongodb using scala

I have connected to mongodb and filter data like this:
val coll = mongoDB.getTable(db, "report")
val query = new BasicDBObject()
query.put("version",getVersion)
val fields = new BasicDBObject()
fields.put("version",1)
fields.put("project",1)
fields.put("uri",1)
fields.put("test",1)
fields.put("browser",1)
val cursor = coll.find(queryObject,fields)
then get a document like this:
{
"_id" : ObjectId("5a968c6cffac6135b09d6cd5"),
"project" : "com.sink.www.helper",
"uri" : "com.sink.www.helper.somketest",
"browser" : "firefox",
"develop" : "scala",
"duration" : "0.61",
"test" : "acceptance"
"version" : "1.0"
"try" : 1
}
{
"_id" : ObjectId("5a968daaffacc7195c2f9b6i"),
"project" : "com.sink.www.helper",
"uri" : "com.sink.www.helper.somketest",
"browser" : "firefox",
"develop" : "scala",
"duration" : "0.62",
"test" : "acceptance"
"version" : "1.0"
"try" : 1
}
{
"_id" : ObjectId("5a968ea5fface1a723ffr246"),
"project" : "com.sink.www.helper",
"uri" : "com.sink.www.helper.somketest",
"browser" : "chrome",
"develop" : "scala",
"duration" : "0.58",
"test" : "acceptance"
"version" : "1.0"
"try" : 1
}
.....
My question is when "version" is specific value like '1.0', then the field try=try + 1, I have write code like this but this will read mongodb every time, this will cost much time:
while (cursor.hasNext())
{
val details = cursor.next()
if (details.get("version").toString() == getVersion && details.get("browser").toString() == getBrowser)
{
try += 1
}
}
because there are much data in mongodb, so it's not adapt to our project. so I want to get specific data to array or others and get to judge then let try+1, I write code like this but report error:
val scenarioArray = coll.find(queryObject,fields).toArray
for (i <- 0 to scenarioArray.length - 1)
{
println(scenarioArray(i))
}
error: value length is not a member of java.util.List[com.mongodb.DBObject]
error: java.util.List[com.mongodb.DBObject] does not take parameters
I don't know how to retrieve the document to array or list or others container, could anyone get to help on this? Thanks.

GrayLog not displaying messages that are Bulk inserted

I need to migrate millions of records from a SQL database to ES. Currently we insert records in ES via GELF HTTP, but only doing that one record at a time just isn't feasible.
I've been working on this a couple days and am new to both GrayLog and ElasticSearch. I'm trying to find a way to Bulk insert messages into ES and then have them display in GrayLog. I've been using Cerebro to monitor the indexes and the number of messages in each of them. When I do the Bulk insert, the message count does increase in the correct Index, however I can not see them in GrayLog.
Here is what I have:
var _elasticsearchContext = new ElasticsearchContext(ConnectionString, new ElasticsearchMappingResolver());
var connectionSettings = new ConnectionSettings(new Uri(ConnectionString))
.MapDefaultTypeIndices(m => m.Add(typeof(Auditing_Dev), "auditing-dev_0"));
var elasticClient = new ElasticClient(connectionSettings);
var items = new List<Auditing_Dev>();
//I loop through a DataReader creating new Auditing_Dev objects
//and add them to the items collection
var bulkResponse = elasticClient.Bulk(b => b.IndexMany(items, (d, doc) => d.Document(doc).Index("auditing-dev_0").Type("message")));
I get back a valid response and I see the document count increase in Cerebro in the auditing-dev_0 index. When I compare a message that I insert via Bulk to one that is inserted via HTTP request, the indexes and types are the same.
Message I insert:
{
"_index" : "auditing-dev_0",
"_type" : "message",
"_id" : "AVsWWn-jNp2NX1vOria1",
"_version" : 1,
"found" : true,
"_source" : {
"level" : 5,
"origin" : "10.80.3.2",
"success" : true,
"type" : "Company.Enterprise",
"user" : "stupid#dropdown.test",
"gl2_source_input" : "57193c1d0cf25a44afc31c15",
"gl2_source_node" : "5866cc80-382e-4287-ae5b-8a0a68a9a1f1",
"gl2_remote_ip" : "10.100.20.164",
"gl2_remote_port" : 52273,
"streams" : [ "578fbabe738a897c6d91336b" ]
}
}
Compared to one inserted via HTTP:
{
"_index" : "auditing-dev_0",
"_type" : "message",
"_id" : "e3d34d50-0a8a-11e7-84bb-00155d007a32",
"_version" : 1,
"found" : true,
"_source" : {
"level" : 5,
"gl2_remote_ip" : "192.168.211.114",
"origin" : "192.168.211.35",
"gl2_remote_port" : 2960,
"streams" : [ "578fbabe738a897c6d91336b" ],
"gl2_source_input" : "57193c1d0cf25a44afc31c15",
"success" : "True",
"gl2_source_node" : "5866cc80-382e-4287-ae5b-8a0a68a9a1f1",
"user" : "admin#purple-pink.test",
"timestamp" : "2017-03-16 22:43:44.000"
}
}
I see the _id is a different format, but does that matter?
In GrayLog there is only one Input and that is the one for GELF HTTP. Do I need to add a new Input?
Turned out to be the Timestamp field not being present. Who knew?

Mongodb data is not returned to nodejs api

I am able to connect to mongodb through my nodejs api but for some reason data is not returned. When i query mongodb from console , here is what i get :
MongoDB Enterprise > db.patients.find();
{ "_id" : ObjectId("58c9a5dd1eb8c7c1c68778ca"), "FName" : "n", "LName" : "ri", "Email" : "abc#yahoo.com", "phone" : "1234567890" }
here is the code from nodejs:
app.get('/api/patients',function(req,res){
Patient.getPatients(function(err,patients){
if(err){
throw err;
}
console.log(patients.length);
res.json(patients);
});
});
and this is getPatients method:
var Patient = module.exports = mongoose.model('patient',patientSchema);
// get patients
module.exports.getPatients = function(callback,limit){
Patient.find(callback);
}
But the browser always shows "[]" and no data. When i look at length of array ( console.log(patients.length)) in API , i get 0. Not sure why data is not returned.
Can someone pls point me what may be the issue ?
Update
Based on suggestions, I did following changes. I created 2 collections just to make sure that the collection exists. So i have patient and patients collections.
MongoDB Enterprise > db.patient.find();
{ "_id" : ObjectId("58cfe4551eb8c7c1c68778cc"), "FName" : "V", "LName" : "K", "Email" : "abc#yahoo.com", "phone" : "1234567890" }
{ "_id" : ObjectId("58cfe4601eb8c7c1c68778cd"), "FName" : "V1", "LName" : "K1", "Email" : "abc#yahoo.com", "phone" : "1234567890" }
MongoDB Enterprise > db.patients.find();
{ "_id" : ObjectId("58cfe42d1eb8c7c1c68778cb"), "FName" : "V", "LName" : "K", "Email" : "abc#yahoo.com", "phone" : "1234567890" }
Here is the code from nodejs file:
var mongoose = require('mongoose');
var patientSchema = mongoose.Schema({
FName: {
type : String
},
LName: {
type : String
},
Email: {
type : String
},
phone: {
type : String
},
},
{collection : 'patient'});
var Patient = module.exports = mongoose.model('patient',patientSchema);
// get patients
module.exports.getPatients = function(callback,limit){
console.log('test2');
Patient.find({}, function(err, patients) {
if (err) throw err;
// object of all the users
console.log(patients.length);
});
}
when i run this code, it prints 'test2' and '0' for me but not actual results. Can someone help with this ?
Are you sure you defined your schemas well and its exported very well... If yes then do something like this from your nodejs scripts
//get the model
var Patient = mongoose.model('patient',patientSchema);
// get all the patients
Patient.find({}, function(err, patients) {
if (err) throw err;
// object of all the users
console.log(patients);
});
I believe this should work
The answer above, while executing the find on the Patient model correctly, will not get the results back to your api response. I think if you change your getPatients code to this:
var Patient = module.exports = mongoose.model('patient',patientSchema);
module.exports.getPatients = function(callback) {
Patient.find({},
function(err, data) {
callback(err,data);
}
);
}
It will work. If that doesn't work, I'd want to see the entire code file to make sure the app.get can access the getPatients function - but you would get an error if that wasn't the case. So, I think this will work.
I figured my code was correct but connection string was incorrect.
Incorrect Connection string :
mongoose.connect('mongodb://localhost:27017/');
Correct connection string:
mongoose.connect('mongodb://localhost:27017/patients');

update nth document in a nested array document in mongodb

I need to update a document in an array inside another document in Mongo DB
{
"_id" : ObjectId("51cff693d342704b5047e6d8"),
"author" : "test",
"body" : "sdfkj dsfhk asdfjad ",
"comments" : [
{
"author" : "test",
"body" : "sdfkjdj\r\nasdjgkfdfj",
"email" : "test#tes.com"
},
{
"author" : "hola",
"body" : "sdfl\r\nhola \r\nwork here"
}
],
"date" : ISODate("2013-06-30T09:12:51.629Z"),
"permalink" : "jaiho",
"tags" : [
"jaiho"
],
"title" : "JAiHo"
}
Q1) Update email of 0th element of comments array
db.posts.update({"permalink" : "haha"},{$set:{"comments.0.email":1}})
This doesn't throw any exception but doesn't update anything as well
Q2) Add a field on nth element of comments array number_likes
db.posts.update({"permalink" : "haha"},{$inc:{"comments.0.num_likes":1}})
Doesn't work either.
Am I missing something here?
Q1: If you update with permalink 'jaiho' instead of 'haha', it most certainly updates the email;
> db.posts.update({"permalink" : "jaiho"},{$set:{"comments.0.email":1}})
> db.posts.find()
..., "email" : 1 },...
Q2: Same goes for this include;
> db.posts.update({"permalink" : "jaiho"},{$inc:{"comments.0.num_likes":1}})
> db.posts.find()
..., "num_likes" : 1 },...
If you are trying to do it dynamically in Node JS following should work.
i = 0;
selector = {};
operator = {};
selector['comments.' + i + '.email'] = 1; // {'comments.0.num_likes' : 1}
operator['$inc'] = selector; // {'$inc' : {'comments.0.num_likes' : 1} }
db.posts.update({'permalink' : 'xyz'}, operator);

Resources