How to access the trello API from within a powerup? - javascript

How can I make queries against the trello API from within a powerup? This seems like such an obvious question but it doesn't seem to be covered that I can find.
My simple powerup looks like this so far:
var boardButtonCallback = function(t){
return t.popup({
title: 'Tools',
items: [
{
text: 'Hide Duplicates',
callback: function(t){
var cardQueryCb = function(result){
console.log(result);
}
var cardQ = 'https://trello.com/1/boards/[board_id]/cards/all';
fetch(cardQ).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
});
return t.cards('id', 'name')
.then(cardQueryCb);
}
}
]
});
};
TrelloPowerUp.initialize({
'board-buttons': function(t, options){
return [{
text: 'Duplicates',
callback: boardButtonCallback
}];
}
});
The response object after the call to fetch says the call is unauthorized.
I would have thought that calling this code from within the context of the power up would be considered authorized. While I'm logged into trello, I'm able to put that address into my browser and get a valid response - how come the javascript call doesn't also result in a valid response?
More importantly, how can I get a successful response from that URL?

Since your power-up is run through an iframe, it's not actually coming from the Trello page itself so you need to specify your API key and token in the GET URL.
Example:
https://api.trello.com/1/boards/560bf4298b3dda300c18d09c?fields=name,url&key={YOUR-API-KEY}&token={AN-OAUTH-TOKEN}
The info for getting your API key and token can be found here: https://trello.readme.io/v1.0/reference#api-key-tokens

Related

Is there a way to fix resource badcfg get error in console

Am getting this error in my console
http://errors.angularjs.org/1.5.3/$resource/badcfg?p0=object&p1=array&p2=GET&p3=https%3A%2F%2Fwww.2tag2.com%2F%2Frequests%2Fapi.php%3Faction%3DgetChat%26id%3D1
Help me resolve this. This is my code service.js
.factory('A', ['$resource',
function($resource) {
;
return {
Chat: $resource(site_url + '/requests/api.php?action=:action&uid1=:uid1&uid2=:uid2', {
action: '#action',
uid1: '#uid1',
uid2: '#uid2'
}),
};
}
])
“To resolve this error, make sure your $resource configuration matches the actual format of the data returned from the server.”
In your case, since the api returns an array, change action=get to action=query.
As stated in the debug:
“By default, all resource actions expect objects, except query which expects arrays.”
Try the following:
var Chat = $resource(
site_url +
'/requests/api.php?action=:action&uid1=:uid1&uid2=:uid2',
{
action: '#action',
uid1: '#uid1',
uid2: '#uid2'
});
var chats = Chat.query({ action: 'getChat', uid1: 1});
chats.$promise.then(function() {
console.log(chats);
return chats;
});
Consider building your API Restfull. In your example above this will mean some altering of your code and api architecture.
To retrieve your chats it is better to build your API calls like below:
Retrieving all chats:
site_url + '/v1/chats'
Retrieving a chat by id
site_url + '/v1/chats/:chatId'

Spotify api add track to playlist

I am using ReactJS and trying to make simple site using the Spotify api.
I am also using the js package spotify-web-api-js. I have succeeded to get the current song playing and able to show it in the browser.
getNowPlaying(){
spotifyApi.getMyCurrentPlaybackState()
.then((response) => {
this.setState({
nowPlaying: {
name: response.item.name,
albumArt: response.item.album.images[0].url
}
});
})
}
//this is from the github link above
Constr.prototype.getMyCurrentPlaybackState = function(options, callback) {
var requestData = {
url: _baseUri + '/me/player'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
But the problem I am facing is to add a track to my playlist. I have tried to use the function replaceTracksInPlaylist from spotify-web-api-js but I cant manage to get it to work, I always get the 403 Forbidden error.
addToPlayList(){
spotifyApi.addTracksToPlaylist(listID, listOfSongID, callback);
}
//this is from the github link above
Constr.prototype.replaceTracksInPlaylist = function(playlistId, uris, callback) {
var requestData = {
url: _baseUri + '/playlists/' + playlistId + '/tracks',
type: 'PUT',
postData: { uris: uris }
};
return _checkParamsAndPerformRequest(requestData, {}, callback);
};
The first example also requires authentication as a access token but why does it not work when adding to a playlist?
I have also changed the scopes to the correct ones that the api documentation says i should use, playlist-modify-public and playlist-modify-private
var scope = 'playlist-modify-public playlist-modify-private user-read-private user-read-email user-read-playback-state';
I can test the api call from the api documentation site and insert my oauth token, track and the playlist id there, and that works fine, I also get this back from the call. I cant think of anything else to try and need some help figuring out the next step.

framework7 component page not working with real database query

In framework7 (latest version) there are some sample pages for e.g. page-loader-component.html. This page having -
<p>Hello {{name}}</p>
and at bottom, there is script
return {
data: function(){
return{
name: "Peter"
}
}
}
Now when the page is accessed, it displays - Hello Peter
Question is I want to fetch name from real database from my server. So I made this changes -
app.request.post(
'http://domain-name/page.php',
{userid: 2},
function(response){
var response = JSON.parse(response);
console.log(response); //console log shows {name: "Peter"}
return response
}
);
return {
data: function(){
return response //console log shows response is not defined
}
}
Now when try to access the page, it throws errors (in console) - ReferenceError: response is not defined. In console my request query is OK, it show - {name: "Peter"}
I did return response as well as tried replacing the position of function as well as tried many other possible fix suggested on stackoverflow.
I think one function is running before other one make finish database queries. I am not expert (just average). So please someone suggest.
I have also tried to access the page through routes.js as example given in request-and-load.html but still reference error.
return response is inside the data: section. The request is not, and they cannot reach each other.
Put the gathering of data inside the data function. You also want to save the response outside of the request function. To make sure the response variable is reachable. I'd also personally move the request itself to be defined in a separate location for usage outside of this one instances.
File: custom.js
requests = {
GetName: function () {
app.request.post(
'http://domain-name/page.php',
{ userid: 2 },
function (response) {
var response = JSON.parse(response);
console.log(response); //console log shows {name: "Peter"}
return response
}
);
},
GetNameDynamic: function (id) {
app.request.post(
'http://domain-name/page.php',
{ userid: id},
function (response) {
var response = JSON.parse(response);
console.log(response);
return response
}
);
}
}
Then inside the data: section call that function and save as a variable. Pass that in the data return.
data: function () {
// Must return an object
var result = requests.GetName();
return {
name: result.name,
}
},
There are other ways/locations to accomplish this. One being the async in the route as the other user mentioned.
In the routes array, just change the path and componentUrl to the correct ones.
{
path: '/post-entity-group/:type/:group/:public/',
async: function (routeTo, routeFrom, resolve, reject) {
var result = requests.GetName();
resolve(
{
componentUrl: './pages/post-entity.html',
},
{
context: {
name: result.name,
}
}
)
}
},
I think you have to pass by async routeto load page context (c.f. F7 doc)
You will be able to load datas via resolve callback
Maybe an example can help : async data for page

Getting x from remote sources and mirroring on to a list

Currently I have this, if with the full app it will create a post with my chosen parameters, however I am very new with vue.js, My aim is to be able to have a text file of such (or other way of storing (json etc)) the values, and then having the js script iterate through the file and display as cards, so for example in the file I would have
"Mark", "http://google.com", "5556", "image"
Or of course using json or similar, I'm up to what ever but my problem is, I don't know how to get values from a remote source and mirror it on to the document, can anyone help?, for clarity here's the snippet of code that I'm using
var app = new Vue({
el: '#app',
data: {
keyword: '',
postList: [
new Post(
'Name',
'Link',
'UID',
'Image'),
]
},
});
-- EDIT --
I'd like to thank the user Justin MacArthur for his quick answer, if you or anyone else doesn't mind answering another one of my painfully incompetent questions. This is the function that adds the cards in a nutshell
var Post = function Post(title, link, author, img) {
_classCallCheck(this, Post);
this.title = title;
this.link = link;
this.author = author;
this.img = img;
};
I can now get the data from the text file, meaning I could do, and assuming I have response defined (that being the http request) it'll output the contents of the file, how would I do this for multiple cards- as, as one would guess having a new URL for each variable in each set of four in each card is not just tedious but very inefficient.
new Post(
response.data,
)
The solution you're looking for is any of the AJAX libraries available. Vue used to promote vue-resource though it recently retired that support in favor of Axios
You can follow the instructions on the github page to install it in your app and the usage is very simple.
// Perform a Get on a file/route
axios.get(
'url.to.resource/path',
{
params: {
ID: 12345
}
}
).then(
// Successful response received
function (response) {
console.log(response);
}
).catch(
// Error returned by the server
function (error) {
console.log(error);
}
);
// Perform a Post on a file/route
// Posts don't need the 'params' object as the second argument is sent as the request body
axios.post(
'url.to.resource/path',
{
ID: 12345
}
).then(
// Successful response received
function (response) {
console.log(response);
}
).catch(
// Error returned by the server
function (error) {
console.log(error);
}
);
Obviously in the catch handler you'd have your error handing code, either an alert or message appearing on the page. In the success you could have something along the lines of this.postList.push(new Post(response.data.name, response.data.link, response.data.uid, response.data.image));
To make it even easier you can assign axios to the vue prototype like this:
Vue.prototype.$http = axios
and make use of it using the local vm instance
this.$http.post("url", { data }).then(...);
EDIT:
For your multi-signature function edit it's best to use the arguments keyword. In Javascript the engine defines an arguments array containing the parameters passed to the function.
var Post = function Post(title, link, author, img) {
_classCallCheck(this, Post);
if(arguments.length == 1) {
this.title = title.title;
this.link = title.link;
this.author = title.author;
this.img = title.img;
} else {
this.title = title;
this.link = link;
this.author = author;
this.img = img;
}
};
Be careful not to mutate the arguments list as it's a reference list to the parameters themselves so you can overwrite your variables easily without knowing it.

Creating a Set With Soundcloud's API

I'm using Javascript to create a web app with Soundcloud's API for my portfolio. At my current stage I need to be able to create a new set (aka playlist). I was using the sample code from Soundcloud's docs:
SC.connect(function() {
var tracks = [22448500, 21928809].map(function(id) { return { id: id } });
SC.post('/playlists', {
playlist: { title: 'My Playlist', tracks: tracks }
});
});
But I'm getting a 422 error:
Unprocessable Entity - The request looks alright, but one or more of
the parameters looks a little screwy. It's possible that you sent data
in the wrong format (e.g. an array where we expected a string).
But it does not look like anything's missing.
The call to the SoundCloud API requires a callback function in addition to the playlist title and tracks. Your code should look like this:
SC.connect(function() {
var tracks = [22448500, 21928809].map(function(id) { return { id: id } });
SC.post('/playlists', {
playlist: { title: 'My Playlist', tracks: tracks }, function(response){
console.log(response)
}
});
});
Their example is, unfortunately, wrong.

Categories

Resources