Error while setting up Extjs Rest Proxy Create function - rest

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.

Related

receiving a 404 error when I make a post request to api server

I've created a custom endpoint for my api server which deletes a single hearing test:
Account.deleteSingleHearingTest = function (req, callback) {
// console.log('accounts.js: deleteSingleHearingTest: are we being reached????', req)
Account.findById(req.accessToken.userId)
.then(account => {
if (!account) {
throw new Error('Cannot find user');
}
console.log('account.js: deleteSingleHearingTest: req.body.hearingTestId N: ', req.body.hearingTestId);
return app.models.HearingTest.updateAll({ accountId: account.id, id: req.body.hearingTestId }, { isDeleted: new Date() });
})
.then(() => {
callback(null);
})
.catch(error => {
callback(error);
});
}
Account.remoteMethod(
'deleteSingleHearingTest', {
http: {
path: '/deleteSingleHearingTest',
verb: 'post'
},
accepts: [
{ arg: 'req', type: 'object', description: 'removes a single hearing test', http: { source: 'req' } }
],
description: 'this is the end point for a single delete',
returns: {}
}
);
I've also updated acls in account.json:
{
"accessType": "EXECUTE",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW",
"property": "deleteSingleHearingTest"
}
Using Postman, I made a POST request to the server address which looks something like :
https://xxx.xxxxxxxx.com/api/Accounts/deleteSingleHearingTest?access_token=XXXXXXXXXXXXXXXXXKyBdxkwxm5s8TSceMgclvXjjrTnyn3UJWIa
The response I get back on Postman is a 404 with the attached message
"Shared class \"Account\" has no method handling POST /deleteSingleHearingTest?access_token=XXXXXXXXXXXXXXXXXXqAoKyBdxkwxm5s8TSceMgclvXjjrTnyn3UJWIa",
The strange thing is, this method was working two weeks ago when I first created, the only difference was that I was running the server locally.
I needed to restart the server so the new methods could be pulled in. For the 1 person who actually reads this. To restart the server the command is pm2 start all

POST vs. GET request differences in Google Analytics API Version 4

Google Analytics v4 API now uses POST requests instead of GET request. And there are no good javascript examples out there yet for me to follow. I'm getting empty object Object { }, but I'm sure that data is there and ViewID is correct!
Any advice on what I am doing wrong? or are there any fully working example that I can follow? Thanks.
requestData = function () {
var url = "https://analyticsreporting.googleapis.com/v4/reports:batchGet?";
var params = {
"reportRequests":[{
"viewId":"12345678",
"dateRanges":[{
"startDate":"yesterday",
"endDate":"today"
}],
"metrics":[{
"expression":"ga:users"
}],
"dimensions": [{
"name":"ga:pagePath"
}]
}]
}
$.ajax({
url: url,
type: "POST",
data: params,
dataType: "json",
success: function(results) {
console.log(results)
},
error: function(xhr, ajaxOptions, thrownError) {
alert('failed');
alert(xhr.status);
alert(thrownError);
}
});
I would highly recommend you use the Google Javascript Client Library to simplify your life greatly. There are plenty of Code Samples using said library:
var DISCOVERY = 'https://analyticsreporting.googleapis.com/$discovery/rest';
// Load the API from the client discovery URL.
gapi.client.load(DISCOVERY).then(function() {
// Call the Analytics Reporting API V4 batchGet method.
gapi.client.analyticsreporting.reports.batchGet( {
"reportRequests":[{
"viewId":"12345678",
"dateRanges":[{ "startDate":"7daysAgo", "endDate":"today"}],
"metrics":[{"expression":"ga:users"}],
"dimensions": [{"name":"ga:pagePath"}]
}]
}).then(function(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}).then(null, function(err) {
// Log any errors.
console.log(err);
});
As for getting jQuery to work, a similar question was asked about nodejs Their solution was to set the content-type=application/json which fortunatly has been Asked and answered as well.
var url = "https://analyticsreporting.googleapis.com/v4/reports:batchGet?";
var data = {
"reportRequests":[{
"viewId":"12345678",
"dateRanges":[{ "startDate":"7daysAgo", "endDate":"today"}],
"metrics":[{"expression":"ga:users"}],
"dimensions": [{"name":"ga:pagePath"}]
}]
}
$.ajax({
url: url,
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(results) {
console.log(results)
},
error: function(xhr, ajaxOptions, thrownError) {
alert('failed');
alert(xhr.status);
alert(thrownError);
}
});

ExtJS5: Get rid of root property in proxy

I'm trying to connect a REST API to my ExtJS application.
For GET /user alike requests I return a response as follows:
{items: [{id: 1, ...}, {id: 2, ....}], total: 2}
So I created a model for that:
Ext.define('model.User', {
extend: 'Ext.data.Model',
fields: [
{ name: 'id', type: 'int' },
{ name: 'name' },
],
proxy: {
reader: {
type: 'json',
totalProperty: 'total',
rootProperty: 'items'
},
type: 'rest',
url: '/Api/User',
}
});
The grids load data and all look perfect. Now I want to be able to request a single record which my api serves as {id: 1, ...}.
But when I do model.User.load(1) the success handler is never triggered because the response doesn't contain items property. If I put my record in that property, it will work but also will look ugly for other API users.
How can I make it work without the root property? I can't find any events for proxy/reader on a model to change it dynamically.
The rootProperty can also be a function, so you could do something like:
rootProperty: function(raw) {
return raw.items ? raw.items : raw;
}

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

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
}
});

Extjs 4.2 Proxy Rest id parameter

I am trying to access a REST service using extjs proxy rest, but the url that is being sent looks weird, take a look:
/rest/v1/distribution-list/1*?id=1*
I dont know why 'id' is being sent.
It shoul send '/rest/v1/distribution-list/1'
Any ideas?
this is my model
Ext.define('Wave.model.DistributionList', {
extend: 'Ext.data.Model',
fields: [
{name: 'id'},
{name: 'name', type: 'string'},
{name: 'status', type: 'string'}
],
proxy: {
type: 'rest',
noCache: false,
reader: {
type: 'json'
},
writer: {
type: 'json'
},
actionMethods: {
create: 'POST',
read: 'GET', // defaults to GET
update: 'POST',
destroy: 'DELETE'
},
api: {
read: '/rest/v1/distribution-list/',
create: '/rest/v1/distribution-list/',
update: '/rest/v1/distribution-list/',
destroy: '/rest/v1/distribution-list/'
}
}
});
Cheers
-Henrique
the ID have been send is setted by Extjs.you can change that using the idParam to changed to other one;
Working with sencha-touch 2.3.1 and rest proxy, ExtJS creates the URL to the action methods with query string parameters, like you said: /rest/v1/distribution-list/?id=1.
If you don't want to append the id, you can change appendId to false inside proxy config.