Getting list with deep=true in Backand - backand

I am having an issue getting relations backing using the deep parameter.
I'm using this url and am expecting it to return my related objects but is not.
url: Backand.getApiUrl() +"/1/objects/blogs?deep=true",

Yes, the deep works only for specific item because of performance reasons.
You should do /1/objects/blogs/1?deep=true
In general we suggest to query the blogs and from the client using promise to get the deep of each one.
If you must get it all at once, you can create server side on demand action, make the query and loop on the results while populating it with the deep. Because it runs on the server side it will be fast. here is a code example for the server-side action:
function backandCallback(userInput,dbRow,parameters,userProfile){
var response=$http({
method: "GET",
url: CONSTS.apiUrl+"/1/objects/blogs",
headers: {
"Authorization": userProfile.token
}
});
var mapping=response.data.map(function(item){
var object=item;
var user=$http({
method: "GET",
url: CONSTS.apiUrl+"/1/objects/users/"+item.author,
headers: {
"Authorization": userProfile.token
}
});
object.author_obj=user;
return object;
})
return mapping;
}

Related

Angular6 - value of response header from one http request to another one as option without nested subscribes

I need to retrieve all specified records from an api endpoint using http get request. The information what is the of total records available is in the X-Total response header.
I tried to retrieve the value of X-Total response header with one http request and then passing the value to another http get request as the value of X-Size header - this approach resulted in nested subscribe:
getTotalRecords () {
return this.http.get('http://localhost:4200/api/loans/marketplace?', {
headers: new HttpHeaders({
'X-Size': '1'
}),
params: new HttpParams().set('rating__eq', 'A').set('fields', 'rating,amount'),
observe: 'response'
})
};
getData() {
this.getTotalRecords().subscribe(data => {
this.http.get('http://localhost:4200/api/loans/marketplace?', {
headers: new HttpHeaders({
'X-Size': data.headers.get('X-Total')
}),
params: new HttpParams().set('rating__eq', 'A').set('fields', 'rating,amount'),
observe: 'response'
}).subscribe(data => {
console.log(data.body);
})
})
};
This works but it seems to me like there has to be a better way of doing this. Also I have this code directly in a component because I wasn't able to make a service out of it - I don't know how to return an observable if I have to subscribe to one to create the other.
Thank you
You can use concatMap to invoke the inner Observable and then share before returning the Observable to make sure you won't make multiple HTTP calls when making multiple subscriptions:
getData() {
return this.getTotalRecords().pipe(
concatMap(data => this.http.get(...)),
share(),
);
}

Loading Data from Behance API in React Component

I am trying to load Behance project data via their API. Whether its localhost or prod, I am getting the following error --
Fetch API cannot load XXX. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Not sure how to solve for this.
My code in the Portfolio component below --
getPortfolio = () => {
const USER_ID = `XXX`,
PROJECT_ID = `XXX`,
API_KEY = `XXX`;
const BEHANCE_URL = `https://api.behance.net/v2/users/${USER_ID}/projects?client_id=${API_KEY}`;
console.log(BEHANCE_URL);
fetch(BEHANCE_URL, {
method: 'get',
dataType: 'jsonp',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then((response) => {
return response.json();
}).then((responseData) => {
return responseData;
}).catch((err) => {
return err;
});
}
UPDATE: Instead of fetch, using jQuery ajax works. --
$.ajax({
url: BEHANCE_URL,
type: "get",
data: {projects: {}},
dataType: "jsonp"
}).done((response) => {
this.setState({
portfolioData: response['projects']
});
}).fail((error) => {
console.log("Ajax request fails")
console.log(error);
});
This seems to have do less with React and more with Behance. What you are getting is a CORS error as you probably figured out. The short explanation is that CORS is a security measure put in on the browser so that websites cannot request other websites from the browser to appear to be the second website. It is a safety measure in place to protect from some phishing attacks.
CORS can be disabled by the server (in this case, Behance) but they decide not to, for legitimate reasons.
Behance would probably allow you to make the request you are trying to make from a server instead. Once you do that, you will need to get the information from your server to your React application, and you will be good to go!

How to properly read POST params with express?

My node app is supposed to POST to an external server, so I'm playing with request from NPM. I want to verify it's working, but I'm not entirely sure I'm doing that right.
I've tried both of these methods
request({
url: url,
method: 'POST',
form: { a: 1}
}
request({
url: url,
method: 'POST',
json: true,
body: { a: 1}
}
In my test when I hit my own server, req.body shows the right object when I do json true. However that just means I'm passing a JSON header. The API I actually need to hit is expecting a normal POST, not JSON.
So when I try to verify that request is working right when I use form, my server says req.body is an empty object.
EDIT
I am posting to external API fine using form, but on my own server, express is leaving request.body as empty object.
See if this works for you:
request.post('http://service.com/upload').form({key:'value'})

Invalid signature Open Bank Project Oauth1.0a

I'm developing a React-Native App with Open Bank Project and I can't use suggested SDKs, not even the nodeJS one as Oauth1.0 is not available in RN.
And I'm stuck with a Bad Signature error on Access Token request '/oauth/token' after passed '/oauth/initiate' and '/oauth/authorize' without any problem.
As specified in docs here before accessing to a Protected Resource we need an Access Token via a POST Request, which gives me the Bad Signature answer.
Here is my code for the request:
getAccessToken(verifier){
let request = {
url: 'https://api.openbankproject.com/oauth/token',
method: 'POST',
data: {
oauth_verifier: verifier,
oauth_token: this.auth.oauth_token,
oauth_token_secret: this.auth.oauth_token_secret
}
}
return fetch(this.url_login, {
method: request.method, //POST
form: request.data,
headers: this.oauth.toHeader(this.oauth.authorize(request))
})
.then((res) => {return res.text()})
.then((txt) => {
console.log('setUID', txt, this.url_login, {
method: request.method,
form: request.data,
headers: this.oauth.toHeader(this.oauth.authorize(request))
})
})
Here is the signed request:
Object {method: "POST", form: Object, headers: Object}
form:
oauth_token:"..."
oauth_token_secret:"..."
oauth_verifier:"71531"
headers:
Authorization:
"OAuth oauth_consumer_key="...", oauth_nonce="3UlQ5dx958tibf6lSg0RUGPQFZeV7b8V", oauth_signature="weyE1lFkoIjAErYLKdSi9SDlCZsNBi7%2BuAkLV2PWePo%3D", oauth_signature_method="HMAC-SHA256", oauth_timestamp="1464248944", oauth_token="...", oauth_token_secret="...", oauth_verifier="71531", oauth_version="1.0""
I've tried with and without Oauth_token_secret, also moving oauth_verifier from body to query but with the same Bad Signature result.
Any idea? thx
You can use oauth module https://github.com/ciaranj/node-oauth
var oauth=require('oauth');
var consumer = new oauth.OAuth(
"https://twitter.com/oauth/request_token", "https://twitter.com/oauth/access_token",
_twitterConsumerKey, _twitterConsumerSecret, "1.0A", "http://127.0.0.1:8080/sessions/callback", "HMAC-SHA1");
then generating signature like this :
var parameters = consumer._prepareParameters("user_access_token", "user_access_token_secret", "http_method", "request_url");
var headers = consumer._buildAuthorizationHeaders(parameters);
parameters array contains signature, also you can build authorization headers if needed. Hope it helps :)

XPages: dijit.Tree dojo.xhrPost and Partial Refresh?

I have a dijit.Tree which works fine. Users can add, delete and rename nodes on this tree (jsfiddle) if they have special authorization on it.
The next step is to post this changes back to the server, which works perfect, using dojo.xhrPost in conjunction with an XAgent (instead of an XAgent this functionality could be achieved using extension library control for REST-Services of type customRestService. However, this is not available until domino version 9...)
Source code:
<xp:button value="Submit tree updates back to server " id="btnSubmit">
<xp:this.onclick><![CDATA[dojo.xhrPost({
url: "folderService.xsp", // XAgent
handleAs: "json",
timeout: 1000,
postData: treeStore._getNewFileContentString(), // treeStore
headers: { "Content-Type": "application/json", "Accept": "application/json" },
load: function(data) {
if (data.success) {
console.log("all folders saved " + data.success);
dojo.byId("#{id:txtMessage}").innerHTML = data.message; ???
dojo.removeClass("#{id:txtMessage}", "lotusHidden"); ???
XSP.partialRefreshGet("#{id:wrapper}", {}); ???
}
},
error: function() {
dojo.byId("#{id:txtMessage}").innerHTML = 'Oops something goes wrong. The update on the folders weren\'t saved.'; ???
dojo.removeClass("#{id:txtMessage}", "lotusHidden"); ???
XSP.partialRefreshGet("#{id:wrapper}", {}); ???
}
});]]></xp:this.onclick>
</xp:button>
Now the question:
I have the requirement to show some information to the user which comes back from the server (load : function(data) {...}).
Possible solutions:
Do it only on client side (e.g. dojo.byId("#{id:txtMessage}").innerHTML = data.message;)?
Pros: No partial refresh needed
Cons: I can't work with already implemented custom controls (e.g. computed rendered property)
Do some partial refresh after a successfull xhrPost?
If this is the right choice, how and were I should implement a partial refresh after a successfull xhrPost?
My feeling says no, because why I should do a partial refresh only for the
making information visible (e.g. rendered property...).
Do something else?
I am not sure which is the best approach to handle my requirements?
Hint: I am working on a Domino Sever 8.5.3 FP6
Thanks in advance for any answer.