Unable to Properly Consume Data from $resource in Angular - ajax

I'm building a prototype app using Parse.com as a temporary backend.
This is how Parse structures its returned data when a request is made.
{
"results": [
{
"playerName": "Jang Min Chul",
"updatedAt": "2011-08-19T02:24:17.787Z",
"cheatMode": false,
"createdAt": "2011-08-19T02:24:17.787Z",
"objectId": "A22v5zRAgd",
"score": 80075
},
{
"playerName": "Sean Plott",
"updatedAt": "2011-08-21T18:02:52.248Z",
"cheatMode": false,
"createdAt": "2011-08-20T02:06:57.931Z",
"objectId": "Ed1nuqPvcm",
"score": 73453
}
]
}
I have a factory that looks like this
app.factory('eventFactory', ['$resource', function($resource){
return $resource('https://api.parse.com/1/classes/Events', {},
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:false},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
});
}
]);
My controller looks like this:
app.controller('currentTradeshowsController', function($scope, eventFactory){
var testSave = eventFactory.get();
console.log(testSave);
console.log(testSave.results);
});
the first console.log for 'testSave' looks like this :
Where as testSave.results returns undefined.
I would think that I would be able to access all the objects this way no?
What am I missing here?
Any help is very much appreciated.

Even though $resource does a very nice job of abstracting, the fact remains that since it works via HTTP calls it runs asynchronously and the code has to be written to handle that semantically. The documentation expresses this.
var testSave = eventFactory.get().success(function () {
console.log(testSave);
});
Unfortunately the Angular docs do not make it clear, but I think the above will work. Possible alternatives are:
.get(function () {
.get({}, function () {
.get().then(function () {
.get().$promise.then(function () {
Find one that works and works best for you. The idea is that the success callback and anything that relies on a successful request need to be in this function.

Related

VueJs not sending data via Inertia to Laravel?

I have question it seems like when I try to send some data via Inertia I dont recieve any in Laravel for some reason any suggestion? Can it have to do something with the fact that the object is proxy object ?
Here are some images:
dd() in php controlelr
console.log() of the object before beeing sent via Inertia
Code of how I send the data + the console log right before sending it
UPDATE:
This is how I add page object to array of pages:
this.Pages.push({
"name": "Untitled",
"icon": "home",
"order": order,
"sections": [],
"DisplayName":true,
"Banner":"Medium",
"Published":"Published",
"DisplayLogo":true,
"media":{
'BackgroundImage': null,
'LogoImage': null,
'BackgroundImageHeight': null,
'LogoImageHeight': null,
'BackgroundImageStyle': {
"value": []
},
"LogoImageStyle": {
"value": []
},
}
});
This is my inertia form:
saveForm: {
applications: [],
},
This is whole save() method:
Save() {
if(this.localProduct.translation.applications.mobile_label[this.currentMobileLabel] != undefined){
if(this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].data == undefined){
this.localProduct.translation.applications.mobile_label[this.currentMobileLabel] = {
"Pages": this.Pages,
"media": this.media,
"name": this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].name,
"active": this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].active,
};
}
else{
this.localProduct.translation.applications.mobile_label[this.currentMobileLabel] = {
"Pages": this.Pages,
"media": this.media,
"name": this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].name,
"active": this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].active,
"data" : this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].data,
};
}
}
this.saveForm.applications = toRaw(this.localProduct.translation.applications);
console.log(this.saveForm);
Inertia.post(this.route(`product.translations.applications`,{translation: this.localProduct.translation.id}),this.saveForm);
},
The applications should be array, the mobile_label should be also array.As it is.
!!!IMPORTANT ALSO!!!
All of this code worked before the project started to shift to vue js 3 and I suppose many libraries had to be updated/exchanged for others.
According to Inertia's documentation the first parameter expected when using Inertia.post() is a URL. Does all of this.route(`product.translations.applications`,{translation: thislocalProduct.translation.id}) return a URL?
To anyone who's having same problem check your array/object assiging to your variables there could be the mistake like in mine I fixed mine with this:
this.saveForm.applications = toRaw(this.localProduct.translation.applications);
var fixed = Object.assign({},this.localProduct.translation.applications);
Inertia.post(this.route(`product.translations.applications`,{translation: this.localProduct.translation.id}),fixed);

HTTP CORS on Graphql server won't insert

I'm working on this project where I have 3 "tables". 2 of them are independent and one is M:M relationship.
However, my database was working fine until I realized it could not liaise the 2 independent table in the 3rd one, so I decided to change up the ids with "_" and make it work like that. However, it keeps returning me the 400 Error and I cant seem to figure out why.
{
"students": [
{
"id": 3021,
"nume": "Name",
"prenume": "Surname",
"an": 3,
"departament": "1"
}
],
"exams": [
{
"id": 1,
"subiect": "Subject",
"data_examen": "02/06/2022 10:00",
"profesor": {
"nume": "Name Surname"
}
}
],
"listexams": [
{
"id":1,
"exam_id":1,
"student_id":3021
}
]
}
Insertion code:
`function send()
{
dategraph.forEach((graph) => {
deInserat={ examenId:graph.examId,studentId:graph.studentId};
obiectInterogare={query:`mutation adaugare($examenId:Int!,$studentId:Int!)
{createListaexamene(examId:$examenId, studentId:$studentId) {id examId studentId}}`,
variables:JSON.stringify(deInserat)}
textInterogare=JSON.stringify(obiectInterogare)
configurari={url:"http://localhost:3000/",
type:"POST",
data:textInterogare,
contentType:"application/json",
success:procesareRaspunsql,
error: (error) =>
{
console.log('Error', error);
}
}
$.ajax(configurari);
});
}`
It's taking the variables from another place but that is working just fine (because it worked prior to changing the fields) but it won't now. Any ideas what it could be?
The error that gets thrown out is
This might help somebody. Beware of the implicit GraphQL schema. The reason why it kept throwing out 400 Error is because I had the M:M relationship keys defined as "int!" instead of "ID!"
As I stated in the question, I knew it's something in the query/database. Thanks to the expert who downvoted it

Cypress: want to partially mock XHR response

I am using Cypress and I want to stub the XHR response partially. I want to catch the original JSON, and edit it partially.
for instance:
cy.route('GET', `**/subjects`, 'fixture:mySubjects.json');
this way i am stubbing the whole response, but I want to see:
original XHR response (of course with many other properties) :
{
'id': 12345,
"subjects": [
{
"key": "mat",
"name": "maths",
"hasAccess": true,
},
{
"key": "eng",
"name": "english",
"hasAccess": false,
}
],
}
what I want to stub is only name, and want to get:
{
'id': 12345,
"subjects": [
{
"key": "mat",
"name": "maths",
"hasAccess": true,
}
],
}
In short, what I wanted to do is to remove the second subject 'eng' from the response. any idea is much appreciated.
Take a look at cy.intercept().
I don't quite understand what parts of the real response you want to return or stub, but this is the mechanism to do so.
cy.intercept('/integrations', (req) => {
// req.reply() with a callback will send the request to the destination server
req.reply((res) => {
// 'res' represents the real destination response
// you can manipulate 'res' before it's sent to the browser
})
})
If you are using a Cypress version < 6 you can try using cy.route2() with the same syntax.

GraphQL Move a child property into parent

I'm looking into GraphQL and got to a question I'm not even sure how to look for in the docs. Probably this isn't even supposed to work, but I'll ask anyway.
I have this query:
query {
organization(login: "facebook") {
repositories(first: 5) {
items: edges {
repo: node {
name
owner {
login
}
}
}
}
}
}
Now, in the response I would like a way to place the login next to name, instead of nested in owner login.
So in the response instead of:
{
...
"name": "react-native",
"owner": {
"login": "facebook"
}
}
I would like to have:
{
...
"name": "react-native",
"ownerName": "facebook"
}
Thank you.
From the specification this is not possible. The response has to be shaped in the way the object types are shaped. There is a project called GraphQL Lodash that gives you a new directive to modify the results. It can be helpful here but it is rather experimental and IMO very undogmatic.

Intel XDK : Parse.com integration "Unauthorized"

I am very new to Intel XDK and i try to make a very simple app like this in that video tutorial: Using Services Datafeed in App Designer.
But instead of the specific service from Rotten Tomatoes i want to integrate a database i have in Parse.com. For that i followed this video tutorial: "Integrating a New Service"
"[https]://software.intel.com/en-us/html5/videos/integrating-a-new-service",
and at the end the response was: "Unauthorized".
Then i found only this answer which comes from Intel's HTML5 Development Forums. I did not get anything either with this. The response was again: "Unauthorized".
And now i am confused and disappointed because:
I can't find other resources to help my self
I don't want to do it someone else instead of me, but
Without a full example, how is supposed to make it to learn?
My code now is similar with this in video: "Integrating a New Service"
In apiconfig.json
{
"MyService": {
"name": "The external service",
"description": "A great API with an external service",
"dashboardUrl": "https://parse.com",
"auth": "key",
"signature": "apiSecret"
}
}
In MyService.js
(function (credentials) {
var exports = {};
exports.ServiceObject = function(params) {
var url = 'https://api.parse.com/1/classes/ServiceObject';
params['apiKey'] = credentials.apiKey;
url = url + '?' + $.param(params);
return $.ajax({url: url, type: 'GET'});
};
return exports;
})
And in MyService.json
{
"endpoints": [
{
"name": "classes",
"dashboardUrl": "https://parse.com/docs/rest",
"methods": [
{
"MethodName": "ServiceObject",
"Synopsis": "Show the entries",
"parameters": [
{
"Name": "objectId",
"Required": "N",
"Default": "",
"Type": "string",
"Description": "The object ID"
},
{
"Name": "text",
"Required": "N",
"Default": "",
"Type": "string",
"Description": "The text"
}
]
}
]
}
]
}
Can someone help me more? In whatever way he thinks best.
Thank you all
Edit:
After the following answer, my problem solved.
"MyService.js" file after the correction is:
(function (credentials) {
var exports = {};
exports.ServiceObject = function(params) {
var url = 'https://api.parse.com/1/classes/ServiceObject';
return $.ajax({
url : url,
headers : {
'X-Parse-Application-Id' : credentials.apiKey,
'X-Parse-REST-API-Key' : credentials.apiSecret
}
});
};
return exports;
})
# user1736947: Your answer was concise and precise, exactly what i needed.
Certainly in the future I will need a lot of help, but for now I can go on my self-education thanks to you.
Thank you very much.
The way the authentication keys are accepted is different for different services. The example in the video.. rottentomatoes.. it accepted keys as a url parameter, so we append the key to the url and send it. However, seems like parse wants the keys in the headers (according to this)
So the equivalent ajax call will be something like :
exports.ServiceObject = function(params) {
var url = 'https://api.parse.com/1/classes/ServiceObject';
return $.ajax({
url : url,
headers : {
'X-Parse-Application-Id' : credentials.apiKey,
'X-Parse-REST-API-Key' : credentials.apiSecret
}
});
This might not fix everything but it will move you a step beyond the authorization issue. Let me know if you are able to retreive the class this way.
To get a particular row entry, append the url with params.objectID.
Also, the XDK services tab has a parse-similar service ... kinvey. It also allows you to create a database online and retreive it.

Resources