How to filter a displayed JSON file - javascript

I'm trying to make a web application using Outlook API's that allows me to search for a specific Outlook contact by his name.
I've got a little knowledge of javaScript but i never used any API or manipulated JSON files beforehand, so i looked through tutorials to help me, and
I ran into this one : https://dev.outlook.com/restapi/tutorial/javascript which i followed and succeeded to implement without much trouble.
Briefly, the tutorial allows me to build an app that can display the last 10 emails from the user, or the contact list of this user, which gives something like that :
Contacts displayed
Now what i'm trying to do is to filter this display and be able to search something like " give the contacts which name contains the syllable "AG" ".
I tried to understand the code as much as i can and i'm almost sure that i have to modify the function displaying all the contacts.
So what i did is that i pasted it, renamed it but now i'm struggling with the query parameters.
function getUserContacts(emailAddress, callback) {
getAccessToken(function(accessToken) {
if (accessToken) {
// Call the Outlook API
var callOptions = {
// Get contacts
url: apiEndpoint + '/Me/contacts',
token: accessToken,
method: 'GET',
email: emailAddress,
query: {
// Limit to the first 100 contacts
'$top': 100,
// Only return fields we will use
'$select': 'GivenName,Surname,EmailAddresses',
// Sort by given name alphabetically
'$orderby': 'GivenName ASC'
}
};
makeApiCall(callOptions, function(result, error) {
if (error) {
callback(null, error);
} else {
callback(result.value);
}
});
} else {
var error = { responseText: 'Could not retrieve access token' };
callback(null, error);
}
});
}
And that's the moment i get totally lost, i tried adding '$where':GivenName='AG' in the query{} section, as well as '$filter':GivenName='AG', but neither of them worked. I searched online for an answer but in every one i founded, the JSON file was "available" ( meaning for me that they have,somewhere this kind of code :
[
{"name":"Lenovo Thinkpad 41A4298","website":"google222"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"}
]
But i don't have this type of code anywhere, so i'm wondering if it is possible to do it like i tried to, or if i have to find a way to retrieve the JSON file in order to obtain something like just above ?
I hope i've been clear enough despite my lack of experience in this field, i'd be glad to give some more details/codes if you ask too !
Thanks in advance and have a great day :)

Thanks to Useless Code and his link i managed to send the right request (error was coming from the fact that filter properties must be listed first in the orderby) from the outlook sandbox and get the expected answer with this URL:
https://outlook.office.com/api/v2.0/me/contacts?$filter=GivenName eq 'AG-Carto'&$orderby=GivenName ASC&$select=GivenName,Surname,EmailAddresses
Now what i'm trying to do is to get my javascript code to send it right.
So i know i have to modify the query{} part of the function, i tried this :
query: {
'$filter': 'GivenName eq AG-carto',
'$orderby': 'GivenName ASC',
'$select': 'GivenName,Surname,EmailAddresses'
}
But when i run it, i got a bad request error, and i see that the url sent by the js code is this one :
https://outlook.office.com/api/v2.0/Me/contacts?%24filter=GivenName+eq+AG-carto&%24orderby=GivenName+ASC&%24select=GivenName%2CSurname%2CEmailAddresses
So i'm obviously seeing that they aren't the same, and i have no idea on how to modify the query{} section so that the URL sent by js is the same as my working URL. If anyone could help me on that i'd be grateful !

Related

Search for artist id by name

I am delving into spotify and javascript is not my main programming language so I managed to get some snippets together from a code that uses ajax (which I would rather not use) but still it returns nothing so I am wondering if some more experienced people out there could help me get started with a template to call the api.
My goal for this test is to search an artist name and get the first result (I expect many names will return multiple artists)
Most of what is in the documentation is curl and I didn't find the demos very helpful.
What I have so far is something like this:
function getArtistName (artistName) {
var artistID;
var searchArtists = function (query) {
$.ajax({
url: 'https://api.spotify.com/v1/search',
data: {
q: query,
type: 'artist',
'accessToken': 'BQBvW70gHJ20Flc8cHErqg8s72bfTePbssblED-gpEuHFr_Yezesbthok8qaKBmjzo2WjWo9J7ZcTpSwvV8MZ_cW_E7UkrG_HF2R6gFQcqfdupgYGmoYsdRdt1q3tq2NU3pPgauuzmFLkUpdAuNp3shdVXJz2SzvnA',
'query': artistName,
limit: '1.'
},
success: function (response) {
//resultsPlaceholder.innerHTML = template(response);
}
});
};
console.log(searchArtists);
return artistID;
}
Some points of confusion:
The key seems to expire. I have a client ID on my profile but I am not sure where I can generate this token other than the "try it out" demo on the site.
What does this actually return, an ID or a JSON?
Here is a demo app that searches tracks using Node.js, or server-side Javascript: https://spotify-quicksearch.glitch.me/
If you click the "Remix this on Glitch" link on the page, you can see and edit the source.
The call to the API is made in server.js. First, we set the client ID and client secret, which are from the dashboard, as you've noted. In this example, we use those to get an access token using the Client Credentials Flow. You can read about all the authentication flows here: https://beta.developer.spotify.com/documentation/general/guides/authorization-guide/
This particular example uses an API wrapper called spotify-web-api-node, which just makes it easier to interact with the API through Javascript functions. To search for artists instead, just change searchTracks to searchArtists.
To answer your second question - all calls to the Spotify API return JSON. You can see the format of the full JSON response here: https://beta.developer.spotify.com/documentation/web-api/reference/search/search/. Roughly, it looks like this:
artists: {
items: [
{
id: <id>,
name: <name>,
...
}
...
]
}
To get the ID from the JSON, you need to parse the JSON object. You can see how I do this in the example in line 21 of client.js. You can modify that code to get just the ID of the first artist like this:
data.artists.items[0].id
Update: made an example that should be even more relevant:
https://spotify-search-artist.glitch.me/

Parse.com Query is empty even though I have data on the server

I'm newbie using parse.com I watched a video tutorial very useful, and now I'm doing my first app. But apparently I think I'm doing something wrong:
I have a Class called MyClass that includes a use. I added a row. In my javascript code I try a simple query by objectId but I'm getting empty results:
var MyClass = Parse.Object.extend("MyClass");
var query = new Parse.Query(MyClass);
query.equalTo("objectId","kX6lNWOpPs");
query.include("user");
query.find({
success: function(results){
console.log("query ok!");
console.log(results);
},
error: function(error){
console.log(error);
}
});
It looks that simple that I'm not sure if I'm doing a huge mistake. The result in the console is:
query ok!
[]
In my class there's a row for sure. I've refreshed the site, even logged out in parse.com. Also the ID is correct, verified a lot of times.
The funny part is that in the video tutorial we used the exact same code, with different classes and data, but same structure.
Thanks in advance for any help. :)
EDIT: if I remove the equalTo and the include functions the results are the same.
EDIT 2: My error was different. I'm ashamed about it :S I had a typo in the Class name: I was using PlayerKey instead of PlayerKeys. The full name doesn't fit on the sidebar column. One of those stupid errors that make you crazy. Besides Parse didn't told me that the class doesn't exists or create it on the query, that only happens as far as I know when you extend. As I said, I'm so newbie :)
If you have the object id then you don't need to run a query as such, you can just get the object with the query:
query.get("kX6lNWOpPs", {
success: function(obj) {
console.log("query ok!");
console.log(obj.id);
},
error: function(object, error) {
console.log(error);
}
});
Note that to use include the user column should be of Pointer type.

Parse iOS SDK: Understanding Cloud Code

Scenario = I am slowly but surely wrapping my head around what is going on with Parse's cloud code features. I just need some help from those who would like to answer some short, relatively simple questions about what is going on in some sample cloud code functions.
The code I will use in this example is below
1) cloud code
Parse.Cloud.define('editUser', function(request, response) {
var userId = request.params.userId,
newColText = request.params.newColText;
var User = Parse.Object.extend('_User'),
user = new User({ objectId: userId });
user.set('new_col', newColText);
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
});
2) called from iOS
[PFCloud callFunction:#"editUser" withParameters:#{
#"userId": #"someuseridhere",
#"newColText": #"new text!"
}];
This code was taken from here
Question 1 =
(request, response)
I am confused by what this is. Is this like typecasting in iOS where I am saying (in the iOS call) I want to pass an NSString into this function ("userId") and inside the cloud code function I'm going to call it "request"? Is that what's going on here?
Question 2 =
Parse.Object.extend('_User')
Is this grabbing the "User" class from the Parse database so that a "PFObject" of sorts can update it by creating a new "user" in the line below it?
Is this like a...
PFObject *userObject = [PFObject objectWithClassName:#"User"]?
Question 3 =
user.set('new_col', newColText)
This obviously 'sets' the values to be saved to the PFUser (~I think). I know that the "newColText" variable is the text that is to be set - but what is 'new_col'? Only thing I can think of is that this sets the name of a new column in the database of whatever type is being passed through the "request"?
Is this like a...
[[PFUser currentUser] setObject: forKey:]
Question 4 =
Parse.Cloud.useMasterKey()
Without getting too technical, is this basically all I have to type before I can edit a "User" object from another User?
Question 5 =
user.save().then(function(user) {
response.success(user);
}
Is this like a...
[user saveInBackgroundWithBlock:]?
and if so, is
function(error) {
response.error(error)
just setting what happens if there is an error in the saveInBackgroundWithBlock?
Please keep in mind, I know iOS - not JavaScript. So try to be as descriptive as possible to someone who understands the Apple realm.
Here's my take on your questions:
The request parameter is for you to access everything that is part of the request/call to your cloud function, it includes the parameters passed (request.params), the User that is authenticated on the client (request.user) and some other things you can learn about in the documentation. The response is for you to send information back to the calling code, you generally call response.success() or response.error() with an optional string/object/etc that gets included in the response, again documentation here.
That's a way of creating an instance of a User, which because it is a special internal class is named _User instead, same with _Role and _Installation. It is creating an instance of the user with an ID, not creating a new one (which wouldn't have an ID until saved). When you create an object this way you can "patch" it by just changing the properties you want updated.
Again, look at the documentation or an example, the first parameter is the column name (it will be created if it doesn't exist), the second value is what you want that column set to.
You have to do Parse.Cloud.useMasterKey() when you need to do something that the user logged into the client doesn't have permission to do. It means "ignore all security, I know what I'm doing".
You're seeing a promise chain, each step in the chain allows you to pass in a "success" handler and an optional "error" handler. There is some great documentation. It is super handy when you want to do a couple of things in order, e.g.
Sample code:
var post = new Parse.Object('Post');
var comment = new Parse.Object('Comment');
// assume we set a bunch of properties on the post and comment here
post.save().then(function() {
// we know the post is saved, so now we can reference it from our comment
comment.set('post', post);
// return the comment save promise, so we can keep chaining
return comment.save();
}).then(function() {
// success!
response.success();
}, function(error) {
// uh oh!
// this catches errors anywhere in the chain
response.error(error);
});
I'm pretty much at the same place as you are, but here are my thoughts:
No, these are the parameters received by the function. When something calls the editUser cloud function, you'll have those two objects to use: request & response. The request is basically what the iOS device sent to the server, and response is what the server will send to the iOS device.
Not quite that. It's like creating a subclass of _User.
Think of Parse objects types as a database table and it's instances as rows. The set will set (derp) the value of 'newColText' to the attribute/column 'new_col'.
Not sure, never used that function as I don't handle User objects. But might be that.
Pretty much that. But it's more sort of like (pseudo-code, mixing JS with Obj-C):
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error){
if(error){
response.error(error); // mark the function as failed and return the error object to the iOS device
}
else{
response.success(user); // mark the function call as successful and return the user object to the iOS device
}
}];

Is it possible to use the Yahoo BOSS OAuth with JavaScript only?

Here is the problem, I have a Google Chrome extension and I want to use the BOSS API in it. The problem is that I do not know if it is possible to use the API without a webserver running.
The documentation does not provide any example using JavaScript. Thus my question:
Is it possible to use the Yahoo BOSS OAuth with JavaScript only?
Probably not...
All the examples Yahoo provides are using server side languages
http://developer.yahoo.com/boss/search/boss_api_guide/codeexamples.html
First you'd have to figure out how to use OAuth with JavaScript, and how will you obscure your API keys from users in a JS File? If you don't have to worry about that, say you are just using this for personal use. Maybe check out the code sample for Node.JS and modify it for your own uses.
http://developer.yahoo.com/boss/search/boss_api_guide/codeexamples.html#oauth_js
function yahooSearch(consumerKey, consumerSecret, query, count,
callback_error_data_response){
var webSearchUrl = 'https://yboss.yahooapis.com/ysearch/web';
var finalUrl = webSearchUrl + '?' + qs.stringify({
q: query, //search keywords
format: 'json',
count: count,
});
var oa = new OAuth(webSearchUrl, webSearchUrl, consumerKey, consumerSecret, "1.0", null, "HMAC-SHA1");
oa.setClientOptions({ requestTokenHttpMethod: 'GET' });
oa.getProtectedResource(finalUrl, "GET", '','', callback_error_data_response);
}
// Use this function to make a call back. Make sure to provide the right key, secret and query for this to work correctly yahooSearch('YAHOO CONSUMER KEY GOES HERE', 'YAHOO CONSUMER SECRET GOES HERE', 'SEARCH QUERY', 10, function(error, data, response){
// enter some code here and access the results from the "data" variable in JSON format
});
You can go to YQL Console and then enter your request, you can select Json or XML, after your result is fetched, look at the bottom of the page and then copy the url. You will be able to use that url inside script tags in an html doc and run it with your browser without a server.

Can I relabel the person.noun for Profile object type in Facebook Open Graph?

I have created a Story using Open Graph and the object I want to use is called Service, which is really just a Profile but I want the text in the post to say 'service' rather than 'person' (which it does now). I have tried creating a custom object but it seems overly complicated for what I need so I have 2 questions:
Can I create a custom type that simply inherits from Profile that can be created in the same way (using the FB.api javascript method)? I don't want to have to use self-hosted types..
Can I simply re-label person.noun from 'person' to 'service' somehow? I can't see a way to do that..
My code to post the story is:
FB.login(function (response) {
if (response.authResponse) {
var strmessage = 'Some message';
var profileid = 'xxxxxxxxx;
var opts = {
profile: profileid,
message: strmessage,
no_feed_story: false,
'fb:explicitly_shared': true
};
FB.api('https://graph.facebook.com/me/mynamespace:myaction', 'post', opts, function (response) {
if (!response || response.error) {
Result("Your message has not been posted");
}
else {
//Message has been posted
Result("Your message has been posted");
}
});
You're going to have to do the custom object if you want a custom name. And, you're going to have to do it on the FB Developer site and go through the whole approval process and all that. And no, there is no way to do any sort of inherence on this.
FB's Open Graph is pretty simple if you use the built in actions and objects, but as soon as you go down the road of wanting custom names for stuff, you are going to have to go all in with it.
I finally put the time aside to implement a custom action and type. It wasn't the most intuitive process but I got there in the end and my app is now approved and doing exactly what I wanted it to do. I'm actually glad I put myself through this learning process as custom stories have great potential and I'm sure I'll find other applications for them in the future.

Categories