How to send facebook api batch request with node.js - facebook

How do I send facebook api batch request with node.js?
FB's examples do not work.

but I finally got danwong/restler.js to work like this:
exports.updateUserFriends = function (userData, next) {
var TOKEN = userData[1];
var fbID = userData[3].id;
var batchreq = {};
batchreq.batch = [];
batchreq.batch.push({"method":"GET", "relative_url":fbID+"/"});
batchreq.batch.push({"method": "GET", "relative_url":fbID+"/friends?limit=50"});
restler.post('https://graph.facebook.com?access_token='+TOKEN,
{data:"batch="+JSON.stringify(batchreq.batch)})
.on('complete', function(data) {
console.log(data);
return next;
});
};
So I thought I'd post this to save someone else a bit of frustration.

First thing to note is that, "Only POST is allowed for batch requests" in FB Api.
var https = require('https');
var url = '/?access_token='+ YOUR_ACCESS_TOKEN_HERE,
batch=[{
"method":"GET",
"relative_url":page + "/insights"
}, {
"method": "GET",
"relative_url":page
}];
url = url + '&batch=' + JSON.stringify(batch);
console.log(url);
var options = {
host:'graph.facebook.com',
path:url,
method: 'POST'
};
var req =https.request(options, function(res){
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
var body='';
res.on('data', function(chunk){
// console.log("body:" + chunk);
body += chunk;
});
res.on('end', function(){
var fbRes = JSON.parse(body);
console.log(fbRes);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();

Related

Sharepoint list item using Api Rest

I need to get a list's items, so I created this function
export function retrieveSPItems(spToken, alias) {
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/ItemCount`;
var myHeaders = new Headers({
Accept: "application/json;odata=nometadata",
Authorization: spToken,
});
return fetch(url, {
method: "get",
headers: myHeaders,
}).then((response) => response.json());
}
As a output I get 3000.
when I change the url to
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/Items`;
I get an empty list!
PS :
It's work in Postman with no problem
The token is generated by adaljs :
Get Token
authContext.acquireToken(SP_BASE_URL, function (error, token){....})
Adal config
export const adalConfig = {
tenant: CURRENT_TENANT,
clientId: CURRENT_APP_ID,
endpoints: {
api: CURRENT_APP_ID,
graph: GRAPH_BASE_URL,
sharepoint: SP_BASE_URL,
},
cacheLocation: "localStorage",
validateAuthority: true,
};
So I need to know :
what the reason fot this issue?
How can I fix it?
It's too general information, you need debug and figure out the detailed error information.
My test demo:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="Scripts/adal.js"></script>
<script type="text/javascript">
var authContext = null;
var user = null;
(function () {
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: 'xxx.onmicrosoft.com',
clientId: '9afc37cb-x-x-x-xxx',
postLogoutRedirectUri: window.location.origin,
endpoints: {
graphApiUri: "https://graph.microsoft.com",
sharePointUri: "https://xxx.sharepoint.com/",
},
cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost.
};
authContext = new AuthenticationContext(config);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
//$errorMessage.html(authContext.getLoginError());
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
user = authContext.getCachedUser();
if (!user) {
authContext.login();
}
//authContext.acquireToken(window.config.clientId, function (error, token) {
// console.log('---');
//})
authContext.acquireToken(window.config.endpoints.sharePointUri, function (error, token) {
alert(token);
if (error || !token) {
console.log("ADAL error occurred: " + error);
return;
}
else {
var listUri = window.config.endpoints.sharePointUri + "sites/lee/_api/web/lists/GetByTitle('mylist')/items?$select=Title";
$.ajax({
type: "GET",
url: listUri,
headers: {
"Authorization": "Bearer " + token,
"accept": "application/json;odata=verbose"
}
}).done(function (response) {
console.log("Successfully fetched list from SharePoint.");
var items = response.d.results;
for (var i = 0; i < items.length; i++) {
console.log(items[i].Title);
$("#SharePoint").append("<li>" + items[i].Title + "</li>");
}
}).fail(function () {
console.log("Fetching list from SharePoint failed.");
})
}
})
}());
</script>

Getting BLOB data from XHR request in ionic 2

Can any one tel that how to GET Blob XHR request and XMLHttpRequest in ionic 2 , i have to fetch image url from the api .
This is my Ajax Code, i want in ionic 2
xhr.open('GET', "https://getbytitle('LE_COE_Mapping')/items(2)/AttachmentFiles('3.jpg')/$value");
xhr.responseType = 'blob';
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// xhr.setRequestHeader('Authorization', 'Token token="' + token + '"');
xhr.setRequestHeader('Authorization', token);
xhr.onload = function (e) {
var img = new Image();
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
document.getElementById('Doctitle').appendChild(img);
// alert(url.createObjectURL(this.response));
};
xhr.send();
Please i am stuck in this from the last two days.
Please Help me.
Thanks
I also got stuck in same problem once then this what I did :
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
//this.response is your final response
console.log(this.response, typeof this.response);
var img = // your img syntax
//your any custom code goes here
}else{
//show error message if you want to show
}
}
xhr.open('GET', 'http://Your image url');// image url be like http://ab.cd/img.png
xhr.responseType = 'blob';
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
//xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//send authorisation if you sending token
xhr.send();
Hope this will help you.
what i solved this below:
this.array: this is the url which we pass to get the blob url of the particular url:
const headers1 = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': "Bearer " + this.accessToken,
'X-Requested-With': 'XMLHttpRequest'
})
const response = await this.http.get(this.array + "/$value", { headers: headers1, responseType: 'blob' }).toPromise();
let b: any = new Blob([response], { type: 'application/octet-stream' });
var url = window.URL.createObjectURL(b);
console.log("this is url BLOB " + url);

How to make restapi call from jasmine-protractor for non-angular app

I am using jasmine-protractor e2e framework to test one of our desktop App. I am totally new to this. So if something is not clear please ask.
This is how I am logging in to the server. Server uses SSO for authentication
describe('Protractor', function() {
beforeEach(function() {
browser.ignoreSynchronization = true
browser.get('https://myserver.com/login.html',60000);
});
it('hi', function () {
var btn = element(by.css('.loginFormGroup')).element(by.partialLinkText('Tegile'));
btn.click();
// browser.ignoreSynchronization = false;
var user = element(by.css('.UsernamePasswordTable')).element(By.id('ctl00_ContentPlaceHolder1_UsernameTextBox'));
user.sendKeys('user');
var pass = element(by.css('.UsernamePasswordTable')).element(By.id('ctl00_ContentPlaceHolder1_PasswordTextBox'));
pass.sendKeys('passwd');
var SignIn = element(by.css('.UsernamePasswordTable')).element(By.id('ctl00_ContentPlaceHolder1_SubmitButton'));
// browser.pause();
SignIn.click();
});
After this i would like to execute restapi on the same server. I want it to use same session if possible.
I tried to use request/request, but didnt work. Maybe i was not using it correctly.
You can simply use nodejs http module to make API calls.Look at below examples on how to make both GET and POST calls using http module.
GET call:
var http = require('http');
var headerObj = { Cookie : 'cookie-value' }
var options = {
host: "localhost" ,
path: "/someurl",
port: 8080,
headers : headerObj
};
var req= http.request(options,function(response) {
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
console.log(body);
});
}).on('error', function (err) {
console.log(err);
});
req.end();
POST call:
var http = require('http');
var data = { name : "somename" }; //data that need to be posted.
var options = {
"method": "POST",
"hostname": "localhost",
"port": 8080,
"path": "/someurl",
"headers": {
"content-type": "application/json",
"cache-control": "no-cache",
cookie: 'cookie-value'
}
};
var req = http.request(options, function (res) {
var body = '';
res.on("data", function (chunk) {
body = body + chunk;
});
res.on("end", function () {
console.log(body);
});
});
req.write(JSON.stringify(data));
req.end();
I used SuperAgent to make REST API calls for my application,
below is the link describes the usage of superagent.
npm package superagent

Post reply on SharePoint online discussion board using REST API

I am trying to post reply on a particular discussion of SharePoint online discussion board through REST API but unable to do it. I don't want to use SP.utilities as this REST API will be called from Android App.
Below is the code which I am implementing:
$.ajax({
url:"../_api/web/Lists/getbytitle(listname)/items?$filter=ParentItemID eq 40",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(itemProperties),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*"
},
success: function (data) {
alert("Successfully posted!!");
},
error: function (error) {
alert("error");
console.log(JSON.stringify(error));
}
});
Instead of creating reply inside discussion, it is creating a new discussion item.
Any help will be highly appreciated.
For creating a message item (reply) in Discussion Board the following properties needs to be specified:
FileSystemObjectType for a message items needs to be set to 0
ContentTypeId- content type Id of message item
ParentItemID - discussion item (container for messages) id
Regarding ParentItemID property
ParentItemID property could not be specified via message payload since it is a read only property, it means the following query for creating a message item fails:
Url /_api/web/lists/getbytitle('Discussions')/items
Method POST
Data {
'__metadata': { "type": "SP.Data.DiscussionsListItem" },
'Body': "Message text goes here",
'FileSystemObjectType': 0,
'ContentTypeId': '<MessageContentTypeId>',
'ParentItemID': <DiscussionItemId>
}
Solution
The following example demonstrates how to to create a message (reply) in Discussion Board via SharePoint REST API.
For creating a message under a discussion item (folder) the following
approach is used: once message item is created, it's getting moved
under a discussion item
var listTitle = "Discussions"; //Discussions Board title
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var messagePayload = {
'__metadata': { "type": "SP.Data.DiscussionsListItem" }, //set DiscussionBoard entity type name
'Body': "Message text goes here", //message Body
'FileSystemObjectType': 0, //set to 0 to make sure Message Item is created
'ContentTypeId': '0x0107008822E9328717EB48B3B665EE2266388E', //set Message content type
'ParentItemID': 123 //set Discussion item (topic) Id
};
createNewDiscussionReply(webUrl,listTitle,messagePayload)
.done(function(item)
{
console.log('Message(reply) has been sent');
})
.fail(function(error){
console.log(JSON.stringify(error));
});
where
function executeJson(options)
{
var headers = options.headers || {};
var method = options.method || "GET";
headers["Accept"] = "application/json;odata=verbose";
if(options.method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: options.url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if("data" in options) {
ajaxOptions.data = JSON.stringify(options.data);
}
return $.ajax(ajaxOptions);
}
function createListItem(webUrl,listTitle,payload){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
return executeJson({
"url" :url,
"method": 'POST',
"data": payload
});
}
function moveListItem(webUrl,listTitle,itemId,folderUrl){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")?$select=FileDirRef,FileRef";
return executeJson({
"url" :url
})
.then(function(result){
var fileUrl = result.d.FileRef;
var fileDirRef = result.d.FileDirRef;
var moveFileUrl = fileUrl.replace(fileDirRef,folderUrl);
var url = webUrl + "/_api/web/getfilebyserverrelativeurl('" + fileUrl + "')/moveto(newurl='" + moveFileUrl + "',flags=1)";
return executeJson({
"url" :url,
"method": 'POST'
});
});
}
function getParentTopic(webUrl,listTitle,itemId){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")/Folder";
return executeJson({
"url" :url,
});
}
function createNewDiscussionReply(webUrl,listTitle, messagePayload){
var topicUrl = null;
return getParentTopic(webUrl,listTitle,messagePayload.ParentItemID)
.then(function(result){
topicUrl = result.d.ServerRelativeUrl;
return createListItem(webUrl,listTitle,messagePayload);
})
.then(function(result){
var itemId = result.d.Id;
return moveListItem(webUrl,listTitle,itemId,topicUrl);
});
}

How to post to facebook serverside with Node.js

As per the question title, I am trying to post to facebook serverside with node.js
Unfortunately there is something wrong with how I am doing it...
I am getting the error
{ [Error: socket hang up] code: 'ECONNRESET' }
app.post('/post/:id?', function(req, res)
{
var id = req.route.params.id;
var token = tokens[id].token;
var path = '/' + id + '/feed?access_token=' + token;
var message = "server side post to facebook";
console.log("post.id = " + req.route.params.id);
var jsonobject = JSON.stringify(
{
'message' : message
});
var options = {
host: 'graph.facebook.com',
port: 443,
path: path,
method: 'post',
headers: {
'content-type': 'application/json',
'content-length': jsonobject.length()
}
};
var req = https.request(options, function(res) {
console.log("statuscode: ", res.statuscode);
console.log("headers: ", res.headers);
res.setencoding('utf8');
res.on('data', function(d) {
process.stdout.write(d);
});
res.on('end', function(){ // see http nodejs documentation to see end
console.log("finished posting message");
});
});
req.on('error', function(e) {
console.error(e);
});
req.write(jsonobject);
req.end();
});
I am not sure exactly what I did, but after lots of hacking it seems to work...
So for anyone who is interested:
app.post('/post/:id?', function(req, res)
{
var id = req.route.params.id;
var token = tokens[id].token;
var path = '/' + id + '/feed?access_token=' + token;
var strToPost = "server side post to facebook";
console.log("post.id = " + req.route.params.id);
var post_data = querystring.stringify({
'message' : 'testing server side post'
});
var options = {
host: 'graph.facebook.com',
port: 443,
path: path,
method: 'POST',
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Length' : post_data.length
}
};
var req = https.request(options, function(res) {
console.log("statuscode: ", res.statuscode);
console.log("headers: ", res.headers);
res.setEncoding('utf8');
res.on('data', function(d) {
console.log("res.on data");
process.stdout.write(d);
});
res.on('end', function(){ // see http nodejs documentation to see end
console.log("\nfinished posting message");
});
});
req.on('error', function(e) {
console.log("\nProblem with facebook post request");
console.error(e);
});
req.write(post_data);
req.end();
});