Is it possible to change the header config of an AngularJS $resource object? - rest

Here's my code:
var userAuth;
var user = $resource('https://myservice.com/user/:id/', {id: '#_id'} ,{
login: {
method: 'POST',
params: {
id: 'login'
},
transformResponse: function(data) {
data = angular.fromJson(data);
userAuth = 'Kinvey '+data._kmd.authtoken;
return data;
}
},
current: {
method: 'GET',
params: {
id: '_me'
},
headers: {
'Authorization': userAuth
}
}
});
I want to be able to use the updated contents of the userAuth variable in the headers of the current endpoint of the resource, after it has been modified in the transformResponse of the login call. Is this even possible? If so, how?
EDIT: I am using Angular version 1.1.3 - this question is about changing the headers in the resource once they have been set, not settings them initially. Thanks

Assuming you are using the current stable release (1.0.8), although this feature is documented in the $resource page it has not been released.
AngularJS resource not setting Content-Type
EDIT:
See my comment below for the explaination of this code.
var customerHeaders = {
'Authorization' : ''
};
var user = $resource('https://myservice.com/user/:id/', {id: '#_id'} ,{
login: {
method: 'POST',
params: {
id: 'login'
},
transformResponse: function(data) {
data = angular.fromJson(data);
customHeaders.Authorization = 'Kinvey '+data._kmd.authtoken;
return data;
}
},
current: {
method: 'GET',
params: {
id: '_me'
},
headers: customHeaders
}
});

Related

How to format axios GET call with nested params

I want to fetch an API
The call look like this;
const instance = axios.create({
method: 'GET',
uri: 'https://api.compound.finance/api/v2/account',
timeout: timeout,
params: {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
},
},
headers: {
"Content-Type": "application/json",
},
});
The API spec https://compound.finance/docs/api
{
"addresses": [] // returns all accounts if empty or not included
"block_number": 0 // returns latest if given 0
"max_health": { "value": "10.0" }
"min_borrow_value_in_eth": { "value": "0.002" }
"page_number": 1
"page_size": 10
}
However the output URI contains some character to replace { } arround max_health value
The uri end up looking like this;
/api/v2/account?block_number=0&page_number=1&page_size=250&max_health=%7B%22value%22:%221%22%7D'
I have tried qs but it's not working as I expect.
I have tryed this to ;
let params = {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
}
}
await instance.get('https://api.compound.finance/api/v2/account',JSON.stringify(params)).then( (response) => {...})
It gave me this error ;
TypeError: Cannot use 'in' operator to search for 'validateStatus' in
{"block_number":"0","page_number":"1","page_size":"250","max_health":{"value":"1"}}
Any help would be appreciated.
The fix;
Use paramSerializer
const instance = axios.create({
method: 'GET',
uri: 'https://api.compound.finance/api/v2/account',
timeout: timeout,
params: {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
},
},
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
headers: {
"Content-Type": "application/json",
},
});

How do I add auth headers to axios hooks requests?

I am working with React Hooks and I want to use the axios hooks package to send an image to Cloudinary.
const [
{ data: putData, loading: putLoading, error: putError },
executePut
] = useAxios(
{
url: 'https://api.myjson.com/bins/820fc',
method: 'PUT'
},
{ manual: true }
)
The docs say nothing about headers?
I believe you are looking for this:
const [
{ data: putData, loading: putLoading, error: putError },
executePut
] = useAxios(
{
url: 'https://api.myjson.com/bins/820fc',
method: 'PUT',
headers: {
'Content-Type': 'application/json'
}
},
{ manual: true }
)
docs: https://github.com/axios/axios#request-config

How to add Item in Folder present in the list using REST API in SharePoint?

The below code successfully adds items in the list, but I want to add item in the folder which is present in the list using REST API, list name is "Designation" and folder name is "Folder1". What changes should I make to insert item in folder?
$.ajax({
url:"https://brillio446.sharepoint.com/teams/Social2016/work/_api/web/lists/getByTitle('Designation')/items",
method:"POST",
dataType:"json",
data: JSON.stringify({
'__metadata': {'type': 'SP.Data.DesignationListItem' },
'Title': 'D1',
}),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
},
success: function(data){
alert("Item added successfully!");
},
error: function(err){
alert("Error while adding item: " + JSON.stringify(err));
}
});
I also find that folder path should be there so I tried this code...
But I got error that 'Path' does no exist in SP.Data.DesigantionListItem
data: JSON.stringify({
'__metadata': {'type': 'SP.Data.DesignationListItem' },
'Title': 'D1',
'Path': '/ServerRelativeUrl of folder',
}),
This is an old question, but search led me here, so adding answer for others.
As Vadim mentioned, /_api/web/lists/getbytitle('ListTitle')/items method does not support adding items to folder.
Instead, you should use /_api/web/lists/GetByTitle('ListTitle')/AddValidateUpdateItemUsingPath method.
Just make sure, you use string values instead of numbers or dates or similar, because it works same as you enter form - parse, validate and save values.
MSDN Reference: Create list item in a folder
Example:
$.ajax({
url:"https://brillio446.sharepoint.com/teams/Social2016/work/_api/web/lists/getByTitle('Designation')/AddValidateUpdateItemUsingPath",
method:"POST",
dataType:"json",
data: JSON.stringify({{
"listItemCreateInfo": {
"FolderPath": { "DecodedUrl": "/ServerRelativeUrl of folder" },
"UnderlyingObjectType": 0
},
"formValues": [
{
"FieldName": "Title",
"FieldValue": "D1"
}
],
"bNewDocumentUpdate": false
}),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
},
success: function(data){
alert("Item added successfully!");
},
error: function(err){
alert("Error while adding item: " + JSON.stringify(err));
}
});
It seems it is not supported to specify folder url while creating list item but you could consider the following approach:
create a ListItem resource
get associated File resource and move it into folder
Example
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("payload" in options) {
ajaxOptions.data = JSON.stringify(options.payload);
}
return $.ajax(ajaxOptions);
}
function createListItem(listTitle,properties,folderUrl){
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
return executeJson({
"url" :url,
"method": 'POST',
"payload": properties})
.then(function(result){
var url = result.d.__metadata.uri + "?$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 = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfilebyserverrelativeurl('" + fileUrl + "')/moveto(newurl='" + moveFileUrl + "',flags=1)";
console.log(url);
return executeJson({
"url" :url,
"method": 'POST',
});
});
}
Usage
var listTitle = "Requests"; //list title
var targetFolderUrl = "/Lists/Requests/Archive"; //folder server relative url
var itemProperties = {
'__metadata': { "type": "SP.Data.RequestsListItem" },
"Title": 'Request 123'
};
createListItem(listTitle,itemProperties,targetFolderUrl)
.done(function(item)
{
console.log('List item has been created');
})
.fail(function(error){
console.log(JSON.stringify(error));
});
Gist

Error while setting up Extjs Rest Proxy Create function

I am using Rest proxy in Extjs Model as:
Ext.define('ThemeApp.model.peopleModel', {
extend: 'Ext.data.Model', fields: [
{ name: 'userId' },
{ name: 'title' },
{ name: 'body'}
],
proxy: {
type: 'rest',
format: 'json',
limitParam:"",
filterParam: "",
startParam:'',
pageParam:'',
url:'http://jsonplaceholder.typicode.com/posts/1',
api: {
read : 'http://jsonplaceholder.typicode.com/posts/1',
create: 'http://httpbin.org/post'},
headers: {'Content-Type': "application/json" },
reader: {
type: 'json',
//rootProperty:'issues'
},
writer: {
type: 'json'
}
In my view I am calling create function as:
var user = Ext.create('posts', {"userId": 124,"title": "sunt","body": "quia"});
user.save();
As I am testing everything on http://jsonplaceholder.typicode.com/ so I am expecting that code will work cause when I test GET and POST functionality via Postman utility everything works fine.
Can anyone point out my error?
I found my mistake.
In the following code I was not setting the correct name of my model, as it won't be "Posts"
var user = Ext.create('posts', {"userId": 124,"title": "sunt","body": "quia"});
user.save();
Also if you are trying with http://jsonplaceholder.typicode.com/ you are not supposed to send ID in the post request.

Share custom story with staged image on Facebook using FB.ui no working

I have the following code that stage the canvas image and then create object to share it using FB.ui. Staging the image and create the object are working without problem but the share dialog not displayed. If I replaced the image parameter in create object with an image url it is working.
is there any wrong in my code:
var userAccessToken = $("#user_access_token").val();
var appAccessToken = $("#app_access_token").val();
try {
blob = dataURItoBlob(dataURL);
} catch (e) {
console.log(e);
}
var fd = new FormData();
fd.append("access_token", userAccessToken);
fd.append("file", blob);
try {
var imageURI;
$.ajax({
url: "https://graph.facebook.com/me/staging_resources",
type: "POST",
data: fd,
processData: false,
contentType: false,
cache: false,
success: function (data) {
console.log("success " + data['uri']);
imageURI = data['uri'];
},
error: function (shr, status, data) {
console.log("error " + data + " Status " + shr.status);
},
complete: function () {
FB.api(
'https://graph.facebook.com/app/objects/myappnamespace:myobject',
'post',
{
access_token : appAccessToken,
object:{
app_id: myappid,
url: "myappurl",
title: "Sample Photo",
image: {
url:imageURI,
user_generated:true
},
description: ""
}
},
function(response) {
var objectId = response['id'];
FB.ui({
method: 'share_open_graph',
action_type: 'myappnamespace:myaction',
action_properties: JSON.stringify({
myobject:objectId
})
}, function(response){});
}
);
}
});
} catch (e) {
console.log(e);
}
finally I found the solution by changing user_generated parameter from true to false
now the code for creating object looks like below:
FB.api(
'https://graph.facebook.com/app/objects/myappnamespace:myobject',
'post',
{
access_token : appAccessToken,
object:{
app_id: myappid,
url: "myappurl",
title: "Sample Photo",
image: {
url:imageURI,
user_generated:false
},
description: ""
}
}