I am using firebase's realtime database and trying to send a put request in a for loop, my code is as follows:
var httpput = function(articleIdlol, versionnumber){
$http({
method: "PUT",
url: FirebaseUrl +articleIdlol+ "/versions/" +versionnumber+"/moment.json",
data: document.getElementById("changeMoment").value
});
}
$scope.changeMomentorSituation = function(articleId){
for (var x = 0; x < $scope.articlesData[articleId].versions.length; x++){
httpput(articleId, x);
}
}
$scope.articlesData contains response.data from an earlier http get request to the firebase database. articleId is a2, I have checked.
I can assure you that the link to the database is correct. However, when I run the code, I am getting a 400 (Bad Request) Error which may mean that the data I am sending is in an incorrect format.
I believe I am sending a string but to be sure I converted the data to a string first and sent it but I get the same error. 'moment' is a key in an object which is contained in an Array called 'versions'.
Here is the JSON schema:
"EditedArticles" : {
"a2" : {
"versions" : [ {
"answer" : "a2",
"article_code" : "a2",
"created_time" : "2016-08-12T01:20:14.300Z",
"datatype" : "article",
"hashtags" : [ "a2", "a2", "a2" ],
"keyword" : "a2",
"moment" : "a2",
"question" : "a2",
"seo" : {
"description" : "a2",
"og_title" : "a2",
"title" : "a2"
},
"situation" : "a2",
"title" : "a2",
"version" : 1
}
}
I tried sending {moment: "xxx"} but this nested another key moment in moment(original) with the value "xxx". This means that, I can use the earlier data and recreate every field in a new object and send it in the data field in the http put request under:
FirebaseUrl +articleIdlol+ "/versions/" +versionnumber.json
but shouldn't I be able to send a single string to modify the value of the key moment assuming that my URL path is correct?
As it turns out, luckily and thoughtfully, Firebase has a http request called PATCH that does exactly what I required. Please refer to: https://www.firebase.com/docs/rest/guide/saving-data.html
As for my solution, here it is:
var httpput = function(articleIdlol, versionnumber){
$http({
url: FirebaseUrl +articleIdlol+ "/versions/" +versionnumber+".json",
method: "PATCH",
data: {"moment":document.getElementById("changeMoment").value}
});
}
$scope.changeMomentorSituation = function(article){
for (var x = 0; x < $scope.articlesData[article].versions.length; x++){
httpput(article, x);
}
}
Observe that if I had used a PUT request as I mentioned, if the URL was
FirebaseUrl +articleIdlol+ "/versions/" +versionnumber+ ".json"
The entire object with 12 keys would be replaced with {moment: "xxx"} BUT if you amend it to a PATCH method request, with the same URL and data fields in the http request, the key 'moment' is updated with the data. Really. This was all.