Cannot update Parse object via REST API - javascript

Right, so I'm simply trying to update my object via the REST API. My request succeeds, I get a 200 response back containing the latest updated timestamp, but the object's column value has not changed.
My Movies class has a title and a genre column, the rights on the class are set to public read write on all rows.
Here is some code
var data = {title:'The Revenant'};
qwest.put('https://api.parse.com/1/classes/Movies/myObjectId', JSON.stringify(data))
.then(function(xhr, response) {
console.log(response);
})
.catch(function(xhr, response, e) {
console.log(e);
});
The response I get back?
{"updatedAt":"2016-01-24T07:59:54.977Z"}
So the request succeeded but if I GET the object again or check in the Parse admin page, the object has not changed. What gives?
EDIT
FYI, if I use the Javascript SDK, I can update the model.
var Movies = Parse.Object.extend("Movies");
var query = new Parse.Query(Movies);
query.get(myObjectId, {
success: function (movie) {
movie.set("title", data.title);
movie.save();
},
error: function (object, error) {
console.log(error);
}
});
This updates the model. For my particular use case though, I would really prefer to use the REST API rather than the SDK, but I guess this means it is not a permissions issue or an id mismatch etc.,

code snippet
qwest.put('https://api.parse.com/1/classes/Movies/Dh7zjiP9KW', data, {dataType:"json",headers:{'x-parse-application-id':'XXX','X-Parse-REST- API-Key':'XXX'}})
.then(function(xhr, response) {
console.log(response);
})
.catch(function(xhr, response, e) {
console.log(e);
});

The response you're getting indicates that the object was updated successfully. Double check that you're looking at the correct object, and that the "updatedAt" field matches the response you saw earlier.
What happens if you fetch the object right away, using the same "qwest" client and https://api.parse.com/1/classes/Movies/myObjectId resource URL (with the correct object id)?

Try removing JSON.stringify(data) and just pass data,

Related

How do I set nested object entries coming from an api?

I got an object where I keep track of several things that the user can fill out, delete, update, etc.
Now, when 'loading' such a project, I make an api call to my backend using axios to retrieve the specific data to send it back to the client. The api call looks like this:
axios.get(`/api/data/${this.$route.params.dataId}`)
.then((response) => {
//Why does this not work?
this.nestedObject = response.data.object
//This DOES work... Why?
this.nestedObject.recipes = response.data.object.recipes
this.nestedObject.cheffs= response.data.object.cheffs
})
.catch((err) => {
console.log("error retrieving data: ", err);
});
Whenever I just set this.nestedObject equal to the data that is coming from the server, it does not work. nestedObject is not updated with the new values. But when I set the individual entries in the object equal to the data that is coming from the server, it does work and nestedObject is updated appropriately. Why is that?

Referencing data I expect to receive from server

new here so apologies if I don't lay this out as you'd expect.
So I'm submitting my reactive form data to the server (mongodb database). I then want to route to a new path passing the ID element that the database returns to the front end as a param in the URL.
This is what I have in the submit function so far:
onsubmit(){
let opdata = null;
this.location.saveOpnote(this.form.value)
.subscribe(response => {
opdata = response
console.log(response)
})
this.route.navigate(['/opnotes/mopsdisplay', opdata._id])
}
So data saves perfectly and backend returns the _id of the new entry. Browser complains:
ERROR TypeError: Cannot read property '_id' of null
My understanding is the browser is looking at this before the asynchronous part of saving to the server is completed and the _id is available.
How do I get round this?
Many thanks.
You want your request to be completed, therefore navigation part should be the last line inside the subscription not outside of it. As your call on save is asynchronous as you mentioned, navigation block gets executed before the save operation finishes.
You can create a new function navigateToMopsDisplay just to navigate to your desired route. Once the Opnotes is saved, the opdata response can be sent to navigateToMopsDisplay with opdata._id and can be navigated
navigateToMopsDisplay(id) {
this.route.navigate(["/opnotes/mopsdisplay", id]);
}
onsubmit() {
this.location.saveOpnote(this.form.value).subscribe(response => {
const opdata = response;
this.navigateToMopsDisplay(opdata._id);
});
}

How to get JSON array on client_JS from server_JS?

From nodeJS (with Express) I try to send JSON_array in response to client JS:
asksJsonArray = JSON.parse(fs.readFileSync("tasks.json", 'utf-8'));
app.get('/getArr', function (req, res) {
readJsonContent();
res.json(JSON.stringify(TasksJsonArray)); //sending JSON array to client_JS in response
});
On client-side I want to get it, but nothing receive:
$.get('/getArr').success(function(res) {
var currencyData = JSON.parse(res);
if (!currencyData.rates) {
// possibly handle error condition with unrecognized JSON response
alert("currency data not found!");
} else {
taskArr = currencyData;
}
})
So I always receive msg 'currency data not found!' ...
res.json already converts the data to JSON, so you don't have to do it manually:
res.json(TasksJsonArray);
I believe this will also set the appropriate headers, so on the client, you don't have to explicitly parse the JSON, jQuery will do it for you:
$.get('/getArr').done(function(currencyData){
if (!currencyData.rates) {
// possibly handle error condition with unrecognized JSON response
alert("currency data not found!");
} else {
taskArr = currencyData;
}
});
Please note that assigning the response to a free variable is not really useful since you won't know when it's "safe" to access the variable. You might want to have a look at How do I return the response from an asynchronous call? .
This may still not work since currencyData might be a value that does not have a rates property. To learn how to correctly access the data, have a look at Access / process (nested) objects, arrays or JSON.
Alter res.json(JSON.stringify(TasksJsonArray)); to res.send(JSON.stringify(TasksJsonArray));.

AngularJS: Cancel overwriting values $resource object after calling save ();

var User = $resource(
'http://test/index.php'
);
var user = User.get({id:'1'});
// GET: http://test/index.php?id=1
// server returns: { "login":"foo", "name":"bar", "mail":"baz" }
user.name = "qux";
user.$save();
// POST: http://test/index.php?id=1
// server returns: { "login":"foo", "name":"bar", "mail":"qux"}
In this case, when you call the save() user object, properties will be replaced by those that came from the server.
But if the server responds like this:
{
"errors":{
"login":"too short",
"name":"is already using that name.",
"mail":"invalid email."
}
}
User object properties are overwritten and instead, property errors containing these mistakes will come up.
Is there a way to change the behavior of $resource? I would like to check the status of the response and, based on that, decide whether to update the properties of an object or report an error to the user.
Angular's $resource is meant to interact with RESTful web services.
In RESTful web services, if there's an error while saving a resource, you should return an appropriate HTTP status (for example, 400).
Then, you can optionally use the error callback:
user.$save(function (response) {
console.log("success!");
}, function (response) {
console.log("error");
});
For a full list of error HTTP statuses:
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error

AngularJS wrapping JSON data returned from server

I have a basic CRUD application up and running, however what I am wanting to do is wrap every response from the server with two additonal parameters namely
'error' => boolean, 'errorMessage' => string, 'data' => {whatever data}
so that I can handle when a successful request is sent and returned from the server, however the database was unable to update for some reason so I can not only keep the UI in sync with the DB, but also present the user an error message on a failed update.
As AngularJS expects an updated object the UI will be in sync if I return the same object on failure, but as there would be no notification of failure the user wouldn't realize what the problem is.
Within my old applications pre-Angular (jQuery based) I could easily decode the json data on every response and if error === true present an error message, but in Angular I cannot seem to figure out how to accomplish this.
I may very well be off base here as I am just getting into Angular so any direction would be helpful.
Make this http request from angularjs and send back a response object from server.
response object --->{'error' => boolean, 'errorMessage' => string, 'data' => {whatever data}}
which gets collected in Resdata. use Resdata to take action.
$http({method: 'POST', url:url, data:body}).success(function(Resdata, status, headers, config) {
console.log(Resdata);
if(Resdata.error == true){
// use Resdata.errorMessage
}
else if(Resdata.error == false){
// use Resdata.data
}
}).error(function(Resdata, status, headers, config) {
console.log("error:", error);
});

Categories