How to use 'find' in Google Sheets API (Cocos Creator) - javascript

I am using Cocos Creator to build a web app that will communicate with google sheets.
I didn't manage to find a suitable client library (as highlighted in below link)
https://discuss.cocos2d-x.org/t/integrating-google-sheets-api/47920
And decided to go with the REST api using http requests.
However, I am unable to find documents that show exactly how to perform the requests i need.
UPDATE:
Updated the title as I realized my previous approach of condition check is meant for filter views, which i misunderstood it's use case.
However, i saw this video showing that you can use the 'find' function that will return the cell grid, which is exactly what i'm looking for.
https://youtu.be/yPQ2Gk33b1U?t=348
I would like to know how to construct the request string to perform this call on the REST api using http request.
Previously:
As the title says, I need a condition check to for searching my sheet and return the cell that has the exact match for a given string.
This link documents that such conditions exist but does not show how to execute it with http request
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other
I've found this post that is performing something very similar to what I wish to request, using FilterCriteria and Condition.
Looking for examples how to use the Google Sheets API FilterCriteria object
However, he is using the C# client library but is there any that I can use for Cocos Creator? As such, I have to perform this with REST using Http Request, and I have no leads on how to construct the request string.
var http = require('http');
var obj = {
'key' : 'MY_API_KEY'
}
var filters = {
'dataFilters': [
{
'Condition' : {
'type' : 'TEXT_EQ',
'values' : [{ 'userEnteredValue' : 'string_to_match' }]
},
}
]
}
var filtersStr = JSON.stringify(filters);
http.Get('MY_GOOGLE_SHEET_ID:getByDataFilter' + filtersStr, obj, function(responseJson)
{
console.log(responseJson);
});
Above code is something i attempted, but you bet it is not working.

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/

Firefox - Intercept/Modify post data when some variable match some pattern

I would like to know if it is possible to intercept and modify a post data when the url and some of the variables meet some pattern.
for example:
let the login url be: http://www.someonlineprofiles.com
let the post data be:
email: "myemail#gmail.com"
pass: "mypass"
theme: "skyblue"
I would like that if:
url = "http://www.someonlineprofiles.com/ajax/login_action_url" and
email = "myemail#gmail.com"
then theme value be unconditionally changed to: "hotdesert"
Is it possible to create a Firefox add-on for that?, are add-ons powerful enough for that?
I found this link:
modify the post data of a request in firefox extension
Thanks in advance!
[ADDED INFORMATION]
I don't know if it is interesting to know the version of my Firefox: 35.0.1
Your question borders on being too broad, so I will give only an overview on how to do this, but not a copy-paste-ready solution, which would take a while to create, and would also deny you a learning experience.
Observers
First of all, it is possible for add-ons to observe and manipulate HTTP(S) requests before the browser sends the request, you just need to implement and register what is called a http observer.
const {classes: Cc, instances: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/Services.jsm"); // for Services
var httpRequestObserver = {
observe: function(channel, topic, data) {
if (topic != "http-on-modify-request") {
return;
}
if (!(channel instanceof Ci.nsIHttpChannel)) {
return; // Not actually a http channel
}
// See nsIChannel, nsIHttpChannel and nsIURI/nsIURL
if (channel.URI.host != "www.someonlineprofiles.com") {
return;
}
doSomething(channel);
},
register: function() {
Services.obs.addObserver(this, "http-on-modify-request", false);
},
unregister: function() {
Services.obs.removeObserver(this, "http-on-modify-request");
}
};
httpObserver.register();
// When your add-on is shut down, don't forget to call httpObserver.unregister();
Do only register the http observer once in your add-on:
If you're using the SDK, then put it into main.js or a dedicated module. You'll also need to rewrite the code a bit and replace the const .. = Components line with a require("chrome").
If you're writing a XUL overlay add-on, put it into a code module.
Rewriting post data
We still need to implement doSomething() and actually rewrite the post data. An http channel usually implements the nsIUploadStream interface, and the upload stream is where the current post data is, if any. It also has a setUploadStream() method, which you can use to replace the upload stream entirely.
function doSomething(channel) {
if (!(channel instanceof Ci.nsIUploadStream)) {
return;
}
// construct new post data
channel.setUploadStream(newStream);
}
Constructing the new post data would be a matter of your actual requirements. I provided a working example in another answer on how you could do it.
If you need to fetch some data from the old upload stream, you'll need to decode the existing channel.uploadStream as multipart/form-data yourself. I suggest you check TamperData and similar add-ons on how they do things there.

How do I access the data given in the onHttpRequest function in the Firefox Add-on SDK?

I am trying to read the response headers 'name' and 'value'. The end goal is to compare them to some pre-set name and a value to see if they match.
Here is what I have so far, it's the function that run every time I get a response header.
var observer = require("observer-service");
observer.add("http-on-examine-response", onHttpRequest);
function onHttpRequest(subject, data)
{
console.log("request subject...." + subject);
console.log("request data...." + data);
}
The output is as follows:
request subject....[xpconnect wrapped nsISupports]
request data....null
I was hoping to know how to get the rest of the data out of the response.
Any help would be great, thanks.
The subject for http-on-examime-response implements nsIHttpChannel, among some other things. You may use .QueryInterface() or instanceof (which internally kinda uses QueryInteface, so that this works as well) to get to that interface.
const {Ci} = require("chrome");
if (subject instanceof Ci.nsIHttpChannel) {
console.log("content-type", subject.getResponseHeader("content-type"));
subject.visitResponseHeaders(function(header, value) {
console.log(header, value);
});
}
There are a couple of other questions around here going into more detail on how to use these notifications... Also, mxr can help a lot checkout out what interfaces there are, how it fits together and how one could use it (in particular the existing tests are great to see some uses for all kinds of stuff).
There is also the "nsITraceableChannel, Intercept HTTP Traffic" article going into more details, e.g. on how to use nsITraceableChannel to get the payload data from such a channel.

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.

Struggling to build a JS/PHP validation function for my app

I have a web service that returns a JSON object when the web service is queried and a match is found, an example of a successful return is below:
{"terms":[{"term":{"termName":"Focus Puller","definition":"A focus puller or 1st assistant camera..."}}]}
If the query does not produce a match it returns:
Errant query: SELECT termName, definition FROM terms WHERE termID = xxx
Now, when I access this through my Win 8 Metro app I parson the JSON notation object using the following code to get a JS object:
var searchTerm = JSON.parse(Result.responseText)
I then have code that processes searchTerm and binds the returned values to the app page control. If I enter in a successful query that finds match in the DB everything works great.
What I can't work out is a way of validating a bad query. I want to test the value that is returned by var searchTerm = JSON.parse(Result.responseText) and continue doing what I'm doing now if it is a successful result, but then handle the result differently on failure. What check should I make to test this? I am happy to implement additional validation either in my app or in the web service, any advice is appreciated.
Thanks!
There are a couple of different ways to approach this.
One approach would be to utilize the HTTP response headers to relay information about the query (i.e. HTTP 200 status for a found record, 404 for a record that is not found, 400 for a bad request, etc.). You could then inspect the response code to determine what you need to do. The pro of this approach is that this would not require any change to the response message format. The con might be that you then have to modify the headers being returned. This is more typical of the approach used with true RESTful services.
Another approach might be to return success/error messaging as part of the structured JSON response. Such that your JSON might look like:
{
"result":"found",
"message":
{
"terms":[{"term":{"termName":"Focus Puller","definition":"A focus puller or 1st assistant camera..."}}]}
}
}
You could obviously change the value of result in the data to return an error and place the error message in message.
The pros here is that you don't have to worry about header modification, and that your returned data would always be parse-able via JSON.parse(). The con is that now you have extra verbosity in your response messaging.

Categories