LOOPBACK REST API for 'LIKE' - rest

how can i type the REST API for "LIKE" Query on LoopBack ?
according to Loopback Documentation,
i already try like this :
ProductDealers?filter={"where":{"DealerCode":"T001","Active":"true","SKU":{"like":"1000.*"}}}
but it nothing happens,
please help me?

It would be something like
Post.find({
where: {
title: {
like: 'someth.*',
options: 'i'
}
}
});
and for api calls
?filter={"where":{"title":{"like":"someth.*","options":"i"}}}
Please take a look at this PR for more info

i found the answer , i didn't know why its can't work when i used brackets " {} "
but when i used " [] " , it works very well, like
Products?filter[where][Name][like]=%25" + valFilter + "%25&filter[where][Active]=1&filter[where][Deleted]=0"
Cheers!

A bit late but i actually found this after looking for something else.
The problem for most people is, that there is something called Url Encoding.
Read more here:
https://en.wikipedia.org/wiki/Percent-encoding
So if you stringify your json filter like in the examples above, make sure you put the stringified object into an Uri Encoder which will make sure you will get what you expect and will control the encoding of your values
let t_filter = {
where: {
title: {
like: 'someth.*',
options: 'i'
}
}
};
let result = encodeURI(JSON.stringify(t_filter));
After that send the result to your Api and not only the stringified Object

Related

Axios - Sending a GET with & sign

I have a GET call (/getTag) that has a variable 'name'.
One of my users created on with a & sign. And unfortunately the GET call is now failing because it looks like this.
/getTag?name=IS&me-1234
Unfortunately my server interprets it like this because of the & sign:
{ id: 'IS', 'me-1234': '' }
Anyone experienced this before and have a way to solve it?
You should use encodeURIComponent on a variable name before passing it to axios.
You can use params key in axios
axios.get('/getTag', {params: {name: 'Is&me123'}})
You should request like:
axios.get('https://your-site.com/getTag', { params: { name: 'IS&me-1234' } });
instead of:
axios.get('https://your-site.com/getTag?name=IS&me-1234');

Fetching json from Mongo with Meteor

I am trying to fetch a json object from the mongodb using meteor, but I have no clue why I’m unable to do so.
I need it to be a JSON object only.
One of the entries of the collection looks like this:
[Image taken from Meteor Dev Tools]
Link: https://i.stack.imgur.com/BxRmS.png
I’m trying to fetch the value part by passing the name.
Code on front end:
export default withTracker(() => {
let aSub = Meteor.subscribe(‘allEntries’);
return {
aBoundaries: DataCollection.find({}).fetch()
}
})(Component Name);
The Meteor Call Statement on front-end:
dataFromDb = Meteor.call(‘functionToBeCalled’, ‘Sydney’);
Server-side Code:
Meteor.publish(‘allEntries’, function(){
return DataCollection.find();
});
Meteor.methods({
functionToBeCalled(aName){
return DataCollection.find({name: aName});
}
});
Another of my questions is:
Is there any way that we publish only all the names in the beginning and then publish the values on demand?
Thanks for your help in advance!
I have tried this as well, but it did not work:
functionToBeCalled(aName){
var query = {};
query['name'] = aName;
return DataCollection.find(query).fetch();
}
The issue seems to be with query.
Collection.find() returns data with cursor.
To get an array of objects, use Collection.find().fetch(). The jsons are returned as collection of array like [{json1}, {json2}].
If there is a single document, you can access the json using Collection.find().fetch()[0]. Another alternative is to use findOne. Example - Collection.findOne(). This will return a single JSON object.
use Meteor.subscribe('allEntries'), do not assign it to a variable.
Meteor.subscribe is asynchronous, it's best you ensure that your subscriptions are ready before you fetch data.
Log DataCollection.find({}).fetch() to your console
Check this official reference https://docs.meteor.com/api/pubsub.html#Meteor-subscribe.
Your second question isn't that clear.
Just in case anyone comes here to look for the answer ~~~
So... I was able to make it work with this code on the server:
Meteor.methods({
functionToBeCalled(aName){
console.log(aName);
return DataCollection.findOne({name: aName});
}
});
And this on the client:
Meteor.call('functionToBeCalled', nameToBePassed, (error,response) => {
console.log(error, "error");
console.log(response, "response"); //response here
})
Thanks for the help!

HttpClient append parameter object to GET request

I'm quite the noob using Ionic or Angular for that matter. So as a cheat sheet I'm using the ionic-super-starter template (link below).
I am trying to make a get request to my API and it works just find if I'm doing it like this:
this.api.get('user/'+this.user.userId+'/entries?include=stuff&access_token=TOKEN');
but when I put the url params into an object it stops working:
let options = {
'include':'stuff',
'access_token':'TOKEN'
}
this.api.get('user/'+this.user.userId+'/entries', options);
The only error I get is "Unauthorized Request" since the options object including the access token was not appended to the url.
In the ionic-super-starter template the providers/api/api.ts calls .set() for each key in my params object:
if (params) {
reqOpts.params = new HttpParams();
for (let k in params) {
reqOpts.params.set(k, params[k]);
}
}
but according to Angular University this is not possible since "HTTPParams is immutable".
If it really was wrong to do this, I don't believe it would be in the ionic template. Nor would I believe that I would be the first person to come across this issue.
However, I am stuck here so any help would be appreciated.
Link to Angular University:
https://blog.angular-university.io/angular-http/#httprequestparameters
Link to ionic-super-starter:
https://github.com/ionic-team/starters/tree/master/ionic-angular/official/super
I think I figured it out myself:
if I write (in my src/providers/api/api.ts)
reqOpts.params = reqOpts.params.append(k, params[k]);
instead of
reqOpts.params.set(k, params[k]);
it works.
if you are using a loopback API as I am you might have nested objects like:
let options = {
"filter": {
"order": "date DESC"
},
"access_token":this.user._accessToken
};
this won’t work. try instead:
let options = {
"filter": '{"order":"date DESC"}',
"access_token":this.user._accessToken
};

Facebook Graph API - Get ID from Facebook Page URL

I have seen this question but what I want is different.
I want to get the Facebook ID not from a general URL (and therefore conditional if it has Like button or not). I want to get the Facebook ID given a Facebook page using the Graph API.
Notice that Facebook pages can have several formats, such as:
http://www.facebook.com/my_page_name
http://www.facebook.com/pages/my_page_name
http://www.facebook.com/my_page_ID
I know I could do some regex to get either the my_page name or my_page_ID, but I am wondering if any one know if GraphAPI is supporting what I want.
It seems to me that the easiest solution to what you describe is to just get the id/name from the url you have using lastIndexOf("/") (which most languages have an equivalent for) and then get "https://graph.facebook.com/" + id.
The data that this url returns has the id (i.e.: 6708787004) and the username (i.e.: southpark), so regardless of which identifier you use (what you extract from the url using lastIndexOf), you should get the same result.
Edit
This code:
identifier = url.substring(url.lastIndexOf("/"))
graphUrl = "https://graph.facebook.com/" + identifier
urlJsonData = getGraphData(graphUrl)
Should work the same (that is result with the same data) for both:
url = http://www.facebook.com/southpark
And
url = http://www.facebook.com/6708787004
(you'll obviously need to implement the getGraphData method).
Also, the 2nd url form in the question is not a valid url for pages, at least not from my tests, I get:
You may have clicked an expired link or mistyped the address. Some web
addresses are case sensitive.
The answer to the question is posted above but the method shown below works fine we do not have to perform the regex on the facebook page urls
I got the answer by this method
FB.api('/any_fb_page_url', function(response){
console.log(response);
});
any_fb_page_url can be any of the following types
https://www.facebook.com/my_page_name
https://www.facebook.com/pages/my_page_name
https://www.facebook.com/my_page_ID
This are also listed in question above
This code is tested on JS console available on Facebook Developers site tools
You can get the page id by using the below api
https://graph.facebook.com/v2.7/smhackapp?fields=id,name,fan_count,picture,is_verified&access_token=access_token&format=json
Reference image
This answer is updated and checked in 2019:
and it is very simple because you do not need to extract anything from the link. for examples:
https://www.facebook.com/pg/Vaireo-Shop-2138395226250622/about/
https://www.facebook.com/withminta
https://www.facebook.com/2138395226250622
https://graph.facebook.com/?id=link&access_token=xxxxxxxx
response:
{
"name": "Vaireo Shop",
"id": "2138395226250622"
}
full nodeJS answer:
async function getBusinessFromFBByPageURL(pageURL: string) {
const accessToken = process.env.fb_app_access_token;
const graphUrl = `https://graph.facebook.com/?id=${pageURL}? access_token=${accessToken}`;
const fbGraphResponse = await Axios.get(graphUrl);
<?php
function getFacebookId($url) {
$id = substr(strrchr($url,'/'),1);
$json = file_get_contents('http://graph.facebook.com/'.$id);
$json = json_decode($json);
return $json->id;
}
echo getFacebookId($_GET['url']);
?>
Thats a PHP example of how to get the ID.
As of Nov 26 2021 none of these solutions work.
Facebook has locked down the API so you need an App Review.
https://developers.facebook.com/docs/pages/overview/permissions-features#features
This answer takes into account that a URL can end with a trailing slash, something that Facebook event pages seem to have in their URLs now.
function getId(url) {
var path = new URL(url).pathname;
var parts = path.split('/');
parts = parts.filter(function(part) {
return part.length !== 0;
});
return parts[parts.length - 1];
}
You can Use Requests and re Modules in python
Code:
import requests,re
profile_url = "https://www.facebook.com/alanwalker97"
idre = re.complie('"entity_id":"([0-9]+)"')
con = requests.get(profile_url).content
id = idre.findall(con)
print("\n[*] ID: "+id[0])
Output:
[*] ID: 100001013078780
Perhaps you can look through the https://developers.facebook.com/docs/reference/api/#searching docs: search against a couple of types and if you find what you're looking for go from there.

Accessing data from response of FB.api()

I am having difficulty accessing the returned JSON response data from the new Facebook JS SDK new Graph API calls.
For instance, in some of their docs where they are using the old way of using the SDK , they get a pointer to the data by response[0]
but here, it's showing that you need to use response.data[0] instead: http://developers.facebook.com/tools/console/ (click on fb.api — photo-albums)
So which is it? I know that with my code below, if I try using response[0] type of syntax to get at the returned JSON I get undefined.
If I use response[0].length I also get undefined
But if I try response.data[0].length I get 2 which I guess is the returned JSON or my 2 albums..I just don't know how to play with this returned object in terms of syntax and manipulating it, its properties, etc.
I want to in the end parse out the returned JSON using the jQuery parseJSON method but have no clue how to even pass the right syntax here for the response and just use that response object.
FB.api(uri, function(response)
{
alert("response: " + response);
// check for a valid response
if (response == "undefined" || response == null || !response || response.error)
{
alert("error occured");
return;
}
alert("response length: " + response.data.length);
}
this alert gave me 2 which makes sense. I have 2 albums.
then I tried something like response.data[0] and tried a jQuery parseJSON(response.data) or parseJSON(response.data[0]) on that and it does not work. So can someone explain the response object here as in regards to Facebook I guess? I see no docs about how to use that returned object at all and how it's constructed.
UPDATED:
Ok, so here's the entire parsing method attempt that I've stubbed out so far. I don't know if the jQuery parsing is 100% good code yet, I sort of stubbed that out but I can't even test that until I figure out how to use this response object coming back. I know it is returning JSON because I parsed another facebook response object in another method in the JS SDK so pretty sure that response[0] or response.data[0] will give you the JSON string.
function GetAllFacebookAlbums(userID, accessToken)
{
alert("inside GetAllFacebookAlbums(userID, acessToken)");
var dFacebookAlbums = {}; // dictionary
var uri = "/" + userID + "/albums?access_token=" + accessToken;
//var uri = "/me/albums";
alert("get albums uri: " + uri);
FB.api(uri, function(response)
{
alert("response: " + response);
// check for a valid response
if (response == "undefined" || response == null || !response || response.error)
{
alert("error occured");
return;
}
alert("response length: " + response.data.length);
for (var i=0, l=response.data.length; i<l; i++)
{
alert("response[key]: " + response.data[i].Name);
}
// parse JSON from response
var dJSONObjects = jQuery.parseJSON(response.data);
alert("dJSONObjects: " + dJSONObjects);
if (dJSONObjects.length == 0)
return;
// iterate through the dictionary of returned JSON objects
// and transform each to a custom facebookAlbum object
// then add each new FacebookAlbum to the final dictionary
// that will return a set of facebookAlbums
$.each(json.attributes, function () {
// add a new album to the dictionary
aFacebookAlbums[i] = FacebookAlbum(
jsonObject["id"],
jsonObject["name"],
jsonObject["location"],
jsonObject["count"],
jsonObject["link"]
);
});
});
return dFacebookAlbums;
}
It depends on the API being used. For the new Graph API single objects come back as top level object: http://graph.facebook.com/naitik -- where as collections come back with a top level data property which is an Array: http://graph.facebook.com/zuck/feed. There's also introspection to make things somewhat easier: http://developers.facebook.com/docs/api#introspection. FQL is the other popular API call, and this is where the top level response is array (think rows in SQL) which is why some examples use response[0]. Easiest thing is to just look at the response in your browser or via curl and see what it looks like.
just to clarify for all you folks who are new to FB.api (as I am) graph queries return different shaped data ... here are two examples:
FB.api('me/' function(returnData) { } ) would put the following data into returnData
{
"id": "592529630",
"name": "Hugh Abbott",
"first_name": "Hugh",
"last_name": "Abbott",
}
then if I said returnData.first_name I would get "Hugh"
If however my query was about my friends, I might run the following query
FB.api('me/friends/' function(returnData) { } )
And the shape of my data is now different:
"data": [
{
"name": "Tom Bell",
"id": "36801805"
},
{
"name": "Michael Royce",
"id": "199712888"
},
]
... so returnData is now a array ... in order to retrieve values, I would do something like the following.
returnData.data[0].name this would return "Tom Bell"
I hope this helps, as I spent a few hours wondering where I had gone wrong ... it turns out, it is all in the shape of the data !!!! good luck my friends.
Hugh
In general, the JS SDK doesn't return JSON object but it returns an object which is structured similar to the JSON Object.
Say for example : One is polling for user events data and according to the GRAPH API reference (http://developers.facebook.com/docs/reference/api/event), the returned data will have attributes as given http://developers.facebook.com/docs/reference/api/event.
The JSON object for the events data would be like this if you are using PHP SDK
Array ( [data] => Array ( [0] => Array ( [name] => sample event [start_time] => 2010-08-09T22:00:00+0000 [end_time] => 2010-08-10T01:00:00+0000 [location] => at office\ [id] => xxxxxxxx [rsvp_status] => attending )) [paging] => Array ( [previous] => hyperlink [next] => hyperlink ) )
But if you are using JS SDK, then the returned response will be like this
response.data[0...n].attributes of the particular table which you are accessing.
So, in the case of event table it will be like this :
response.data[0...n].name or response.data[0...n].id, response.data[0...n].end_time, etc
Did this ever get figured out. No one accepted anything.
alert("response[key]: " + response.data[i].Name);
The above code has Name and not name. Also, as Matti pointed out above, this works:
response.data[0].name
Just my two cents. #CoffeeAddict, accept answers to show some appreciation... Seems like someone with you rep would appreciate that. :o)
I haven't looked at the API, but I doubt FB would give you JSON encoded strings in an array. Have you tried just accessing response.data[0].someproperty?
If there is no error, then response.data should be the stuff you want (this will be an array in most cases) if you are using the new graph api. You could always just alert the JSON string if you are unsure what you are getting back.
I'm sure this must not be an issue anymore considering the Graph API explorer clearly displays the data in the form that it is returned. You are right about the difference in structure of the responses, but personally it has been useful to see what data is returned using the explorer and use the syntax accordingly.