Maybe its a very newbie question for here but i spend a lot of time to see a good approach for doing this and i didn't find convenient answer. I am trying to make a simple call to a rest api and i want to pass a value with the GET request appended to the string. like url/foo where foo is the parameter. I have a query variable that i want to append to the end of the url string for the get request. Thank you in advance.
class About extends React.Component {
constructor(props) {
super(props);
this.state = {
products: [],
filteredItems: [],
user: {},
query: '' <-- query variable to be appended to the end of the get request
};
}
componentDidMount() {
fetch(`'myurl/${this.state.query}'`) <-- i want to append the variable at the end of the string ??
.then(res => res.json())
.then((result) => {
console.log(result);
this.setState({
products: result,
filteredItems: result
});
}
)
}
queryChange = (evt) => {
this.setState({query: evt.target.value}) <-- update the variable state from an event
}
Get rid of the extra quotations (') in 'myurl/${this.state.query}'
let query = {id:1};
let url = 'https:example.com//xyz.com/search?' + query;
fetch(url)
You can pass param without using `` or $ also,In componentDidMount()
componentDidMount() {
let query = this.state.query;
fetch('myurl/'+query)
.then(res => res.json())
.then((result) => {
console.log(result);
this.setState({
products: result,
filteredItems: result
});
}
)
}
Related
I would like to validate and set a ID for a collection in firebase. Right now i am just trying to get an id number back from a collections query and send it to the function that needs it. Here is the function that needs the id#.
const data = lastCustIdGrab(); console.log(`Last number ${data}`);
This is the return sender. I can get the document Id in the console log but can't figure how to send it back.
exports.lastCustIdGrab = () => {
db.collection('Customers')
.orderBy('createdAt', 'desc')
.limit(1);
.get()
.then((data) => {
let DOC = data.docs[0];
let ID = DOC.id;
console.log("LOOOP ",ID);
return ID;
})}
This gets me the id in the LOOOP output but won't return it! I know i can return data as i have tested with the arbitrary code below and it works. The return sends it back to be console logged in the "last number" output properly.
exports.lastCustIdGrab = () => {
let ID = 12345;
return ID;
}
So I'm sure that i am just missing something simple. Thanks for the Help!
In the lastCustIdGrab function you need to return the promises chain, as follows:
exports.lastCustIdGrab = () => {
return db.collection('Customers') // <== See return
.orderBy('createdAt', 'desc')
.limit(1);
.get()
.then((data) => {
let DOC = data.docs[0];
let ID = DOC.id;
console.log("LOOOP ",ID);
return ID;
});
}
AND you should note that the lastCustIdGrab function is asynchronous and returns a Promise, which means that you need to do:
lastCustIdGrab()
.then(data => {
console.log(`Last number ${data}`);
});
.get() is asynchronous, and in your method you're not returning the promise. So even though the then() is executing, the value returned from the promise's resolve isn't being returned to lastCustIdGrab() invocation because the promise is never returned. So (switching it up to use async/await) try this:
exports.lastCustIdGrab = async () => {
let data = await db.collection('Customers')
.orderBy('createdAt', 'desc')
.limit(1)
.get();
let DOC = data.docs[0];
let ID = DOC.id;
return ID;
}
}
And in your invocation wait for the promise to resolve to ensure error handling and method completion:
const data = await lastCustIdGrab();
I am calling an AWS Lambda function written in NodeJS which exports:
exports.handler = (event, context, callback) => {
The callback is passed the output of a SQL query:
new mssql.Request(conn).query(passedStatement,(err, result) => {
if (err) {
callback(err);
} else {
console.log("done");
callback(null, result);
}
});
I am calling this function from Java code:
InvokeRequest request = new InvokeRequest()
.withFunctionName(lambdaFunctionName)
.withPayload(jsonPayload)
.withInvocationType(InvocationType.RequestResponse)
.withLogType(LogType.Tail);
InvokeResult result = client.invoke(request);
The log result contains the message 'done' so I believe the code executed without errors. However, I can't see how to get the output from the SQL query. Assuming I pass SELECT * FROM user WHERE Username = 'My User', how do I get user details in the Java code?
In order to get the result callback as JSON all that is required is:
new String(result.getPayload().array())
I use the following code to post :
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(VERIFY_PAYMENT_ACTIONURL);
// key is the parameter
// MERCHANT_KEY is the value
method.addParameter("form", "2");
method.addParameter("key", MERCHANT_KEY.trim());
method.addParameter("command", VERIFY_PAYMENT_COMMAND.trim());
method.addParameter("hash", hash);
method.addParameter("var1", transactionID.trim());
method.addParameter("salt", ALGORIHTM_SHA512_SALT_KEY.trim());
int statusCode = client.executeMethod(method);
if (statusCode != -1) {
in = method.getResponseBodyAsStream();
}
String text = method.getResponseBodyAsString();
System.out.println("text : "+text);
method.releaseConnection();
} catch (Exception e) {
e.printStackTrace();
}
and I get the response text as follows :
a:3:{s:6:"status";i:1;s:3:"msg";s:44:"1 out of 1 Transactions Fetched Successfully";s:19:"transaction_details";a:1:{i:2298597;a:15:{s:8:"mihpayid";s:18:"403993715508098532";s:10:"request_id";N;s:12:"bank_ref_num";N;s:3:"amt";s:5:"53.77";s:4:"disc";s:4:"0.00";s:4:"mode";s:2:"CC";s:7:"PG_TYPE";s:4:"AXIS";s:7:"card_no";s:16:"512345XXXXXX2346";s:12:"name_on_card";s:3:"emu";s:4:"udf2";s:1:"0";s:7:"addedon";s:19:"2013-06-03 17:34:42";s:6:"status";s:7:"failure";s:14:"unmappedstatus";s:6:"failed";s:12:"Merchant_UTR";N;s:10:"Settled_At";N;}}}
now I want to extract the above output and put it into map like "transactionid" and other details like the following format
array('status' => '1',
'msg' => 'Transaction Fetched Successfully',
'transaction_details' =>
array(
'mihpayid' => Transaction ID,
'request_id' => Request ID,
'bank_ref_num' => Bank Reference Number,
'amt' => Amount
'disc' => Discount
'mode' => Transaction Mode (NB for Netbanking, CC for credit card, DC for Debit card, "-" for
'status' => Transaction Status
unknown)
)
);
I really do not find any common way to extract the above output. will some one help to do this?
or is it possible for me to convert the above to JSON and put them in to a map like the above?
thanks
I don't recognise it but are you sure it's not a well know format?
To turn it into JSON you'd need to
1)remove every instance of a character that is followed by a colon (and the colon)
2)replace every other semi-colons with a comma
3)replace all the other semi-colons with colons
And you'd need to do all that while taking into account that strings could contain any of those things.
From comments:
The string is in PHP serialised form. This library parses it: https://code.google.com/p/serialized-php-parser/
I'm trying to get all the associated products for a configurable product using the Magento SOAP API v2. The catalogProductLink call looks close, but doesn't handle configurable types. I don't see any other calls that contain the associated product and configurable type information for a product. How have others solved this issue?
I'm using Magento version 1.6 and the SOAP API V2 with Java.
I looked deeper into this solution and realized that you may need to override the API model (Mage_Catalog_Model_Product_Api) to achieve the results you're looking for.
In the items function (around line 90), you can do something like this:
foreach ($collection as $product) {
$childProductIds = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($product->getId());
$result[] = array(
'product_id' => $product->getId(),
'sku' => $product->getSku(),
'name' => $product->getName(),
'set' => $product->getAttributeSetId(),
'type' => $product->getTypeId(),
'category_ids' => $product->getCategoryIds(),
'website_ids' => $product->getWebsiteIds(),
'children' => $childProductIds[0],
);
}
create the folder app/code/local/Mage/Catalog/Model/Product/Link
copy the app/code/core/Mage/Catalog/Model/Product/Link/Api.php into this folder and edit it. (I’ve only done the change for the V1 but I’m pretty sure it’s as easy in V2)
replace the content of the the items() function with the following
if($type == "associated"){
$product = $this->_initProduct($productId);
try
{
$result = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null,$product);
}
catch (Exception $e)
{
$this->_fault('data_invalid', Mage::helper('catalog')->__('The product is not configurable.'));
}
}
else
{
$typeId = $this->_getTypeId($type);
$product = $this->_initProduct($productId, $identifierType);
$link = $product->getLinkInstance()
->setLinkTypeId($typeId);
$collection = $this->_initCollection($link, $product);
$result = array();
foreach ($collection as $linkedProduct) {
$row = array(
'product_id' => $linkedProduct->getId(),
'type' => $linkedProduct->getTypeId(),
'set' => $linkedProduct->getAttributeSetId(),
'sku' => $linkedProduct->getSku()
);
foreach ($link->getAttributes() as $attribute) {
$row[$attribute['code']] = $linkedProduct->getData($attribute['code']);
}
$result[] = $row;
}
}
return $result;
then you can call the API like this now:
$client->call($sessionId, 'product_link.list', array('associated', $id_of_your_configurable_product));
Basically my code is checking the type provided and if it’s “associated” it returns the child products.
I’m pretty sure there’s better way of doing it but I thought that the Product Link API was the most relevant place to do it.
Enjoy!
(please note: this code is not mine, i just adapted it and thought it would be a nice idea to help you guys out)
in facebook fql theres this code
https://developers.facebook.com/docs/reference/api/batch/
curl \
-F 'access_token=…' \
-F 'batch=[ \
{"method": "GET", "relative_url": "me"}, \
{"method": "GET", "relative_url": "me/friends?limit=50"} \
]'\
https://graph.facebook.com
it suppose to to be sent with json
but I really dont understand how to do this
any help ?
thanks
You can simple use the BatchFB api its very powerful and easy , you dont have to deal will all of these stuff and it use the fql
for example to get all your friends
Later<ArrayNode> friendsArrayList = this.Batcher.query("SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())");
for (JsonNode friend : friendsArrayList.get()) {
.......
}
and its batched
I believe your question is how to execute a batch request using Facebook Graph API. For this you have to issue a POST request to
"https://graph.facebook.com"
and the post data to be sent should be
"batch=[{'method': 'GET', 'relative_url': 'me'}, {'method': 'GET', 'relative_url': 'me/friends?limit=50'}]&access_token=#accesstoken"
in your case [#accesstoken must be replaced with your access token value].
This request will return the details of the owner of the access token(normally the current logged in user) and a list of 50 facebook friends(contains id and name fields) of the user along with page headers(can be omitted).
I am not sure whether you meant java or Javascript. Please be specific on it.
I am a C# programmer basically. Will provide you a code to execute the above request in C# here.
WebRequest webRequest = WebRequest.Create("https://graph.facebook.com");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-UrlEncoded";
byte[] buffer = Encoding.UTF8.GetBytes("batch=[{'method': 'GET', 'relative_url': 'me'}, {'method': 'GET', 'relative_url': 'me/friends?limit=50'}]&access_token=#ACCESSTOKEN");
webRequest.ContentLength = buffer.Length;
using (Stream stream = webRequest.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
using (WebResponse webResponse = webRequest.GetResponse())
{
if (webResponse != null)
{
using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string data = streamReader.ReadToEnd();
}
}
}
}
Here the variable data will contain the result.
Salah, here is the example i use as reference, i am sorry though i do not remember where i found.
FB.api("/", "POST", {
access_token:"MY_APPLICATION_ACCESS_TOKEN",
batch:[
{
"method":"GET",
"name":"get-photos",
"omit_response_on_success": true,
"relative_url":"MY_ALBUM_ID/photos"
},
{
"method": "GET",
"depends_on":"get-photos",
"relative_url":"{result=get-photos:$.data[0].id}/likes"
}
]
}, function(response) {
if (!response || response.error) {
console.log(response.error_description);
} else {
/* Iterate through each Response */
for(var i=0,l=response.length; i<l; i++) {
/* If we have set 'omit_response_on_success' to true in the Request, the Response value will be null, so continue to the next iteration */
if(response[i] === null) continue;
/* Else we are expecting a Response Body Object in JSON, so decode this */
var responseBody = JSON.parse(response[i].body);
/* If the Response Body includes an Error Object, handle the Error */
if(responseBody.error) {
// do something useful here
console.log(responseBody.error.message);
}
/* Else handle the data Object */
else {
// do something useful here
console.log(responseBody.data);
}
}
}
});