Firebase simple REST DELETE? - angularjs

My data in firebase looks like the below. I am reading https://www.firebase.com/docs/rest/api/ and its weird, I am trying to remove an item.
burning-*
contacts
-K7qAf6egBeg5l3e_Gjc
name: "Ind"
phonenumber: "(408) ***-***"
uid: "1"
-K7qB8Afu7bIm9LUtV68
name: "Paul Bhayya"
phonenumber: "(408) ***-***"
uid:"2"
Inside angular.js I am making this call inside a custom directive of mine.
$http.delete(Firebaseurl + '/contacts/'+scope.contact.name+'/.json').then(function(result) {
console.log(result);
});
The api is not making sense to me, I see the problem might be that my data is now nested inside a key with a weird ID i.e -K7qAf6egBeg5l3e_Gjc.
So I am wondering how can I make a call to delete an item by the key name so if client side that contact is clicked say Ind gets clicked then I tell Firebase to delete the contact with that name. Maybe ID is better, but whatever works.
EDIT:
FYI I parsed the Firebase object selectedContacts is the result of the GET method for the objects. It wasnt formatted very well for my angular code so I turned it into a clean array of objects and I am using it to compare to other set of data to pass into the $scope
Object.keys(selectedContacts.data).forEach(function(key) {
selectedContactsArray.push(selectedContacts.data[key]);
});
selectedContactsArray.filter( function( item ) {
for( var i=0, len=usersContacts.length; i<len; i++ ){
if( usersContacts[i].name == item.name ) {
usersContacts[i]['selectedContact'] = true
}
}
});

To get a user by their name:
...firebaseio.com/contacts.json?orderBy="name"&equalTo="Ind"&limitToFirst=1
You'll have to add an index to your security rules:
{
"rules": {
"contacts": {
".indexOn": ["name"]
}
}
}
With this index, the query will return an object like this:
{
"-K7qAf6egBeg5l3e_Gjc": {
"name": "Ind",
"phonenumber": "(408) ***-***",
"uid": "1"
}
}
You can read the key from there and then execute a REST DELETE request against
...firebaseio.com/contacts/-K7qAf6egBeg5l3e_Gjc.json
But as discussed in the comments to your question, you can also use AngularFire to do the same.

Related

Access individual JSON array item and use for blog post dynamically

I'm building a simple Nuxt JS blog with a blog.json file containing an array of blog posts which contains:
Title (String)
Body (HTML markup)
Creation (Date)
I will attach the format of this shortly. I know how to iterate over each array item and display it on the page, and I also have a basic understanding and some basic experience with dynamic routing in Nuxt JS.
The problem I'm currently facing is I need to be able to access individual array items and use them as blog posts, e.g: pages/blog/_slug where _slug would be the title of a blog post, with hyphens + all lowercase automatically.
I'm wondering how I would access for instance the Winter blog post in my example and be able to go to mysite.com/blog/winter-blog-post using the following JSON format:
{
"blogs": [
{
"title": "Summer blog post",
"body": "<div class=\"post\">My blog content</div>",
"created": "2019-03-14 10:08:00"
}
{
"title": "Winter blog post",
"body": "<div class=\"post\">My blog content</div>",
"created": "2019-03-15 10:08:00"
},
{
"title": "Spring blog post",
"body": "<div class=\"post\">My blog content</div>",
"created": "2019-03-16 10:08:00"
}
]
}
I essentially want to be able to go to mysite.com/blog/winter-blog-post and have it use the content from that particular array item.
I'll assume you have your pages set up correctly and you can reach /blog/_slug, so it really is just a matter of passing the required params and converting them as needed. In blog.vue you would have a list of your posts and a click on something would navigate to the full article. That click event would trigger a method where you can manipulate the title and use it as a param. So if you have a 'Read More...' button you would assign #click="readMore(blog.title)" to that button.
Then in your methods you take the passed 'title' parameter, change it as you want, and trigger the route change.
methods: {
readeMore(title) {
let passedTitle = title.toLowerCase()
passedTitle = passedTitle.replace(" ", "-")
this.$router.push('/blog/' + passedTitle)
}
}
Then in your _slug.vue you take the passed param, change it back and use that to find your article.
export default {
asyncData({params, $axios }) {
let title = params.passedTitle.replace("-", " ")
let oldTitle = title.charAt(0).toUpperCase() + title.slice(1)
// make your query however you do, if with axios...
$axios.get('/posts', {
params: {
title: oldTitle
}
})
//or if its a vuex state item...
//let post = this.$store.state.posts.find((p) => p.title === oldTitle)
return post
},
}

AngularJS - Calling values in response with Spring GET

New here so my description might be bad but I'm trying to access the values on the second level of my JSON but I can't seem to get it. It only brings the values of the top level.
My JSON body looks like the following:
{
"services": [
{
"nameLevel1": "Example1",
"secondServices": [
{
"id": 1,
"namelevel2": "Example2",
}
]
}
]
}
And when I call it, I only can get the nameLevel1 and that is it. My GET method is this:
$scope.retrieveServices = function (id) {
SpringDataRestService.get(
{
"collection": "user",
"resource": id
},
function (response) { // Success Function
$scope.userServices = response.services;
$scope.recievedValues = true;
}
);
};
Now I originally thought all I would have to do is:
$scope.userServices = response.services.secondServices;
But I'm getting an undefined issue. So my query is how do I access all of them? My JSON body when doing a log output does show everything, but for some reason I can't seem to get it to show everything in my table. Only the nameLevel1 values.
Any help would be appreciate, and I hope my description is okay. Edits would be get as well since not too sure if I have labelled this correctly. Thank you!

Working with angular cached array object

So I create a cached json object within an array with the following method in Angular:
$scope.saveClaim = function() {
//always set isOffset to false - empty string does not work for non-string objects in web api when field is required
$scope.claimInfo.isOffset = false;
$scope.claimsSubmit.push($scope.claimInfo);
//clears scope so form is empty
$scope.claimInfo = {
id: "",
benefitId: "",
isSecIns: "",
isNoResId: "",
expenseTypeId: "",
fromDate: "",
toDate: "",
provider: "",
who: "",
depId: "",
age: "",
amount: "",
comments: "",
isOffset: ""
};
}
The idea is the user fills out a form, and at the end either selects to add another claim or submit a claim (the object). After each time the form is filled and user selects file or add another, the form clears and the user then enters more data. The results is an array of object(s) that look like:
[
{
"id": "",
"benefitId": "",
"isSecIns": "",
"isNoResId": "",
"expenseTypeId": "",
"fromDate": "",
"toDate": "",
"provider": "",
"who": "",
"depId": "",
"age": "",
"amount": "",
"comments": "",
"isOffset": false
}
]
If more than one claim is entered, then we get multiple objects with same properties.
Each claim is then displayed with limited data in info boxes that display only 3-4 of the properties.
So I am trying to figure best way to do 3 things. First, add a unique "id" to each object. Second, if the delete icon in the info box selected, then remove that object from the array and if the "edit" icon is selected in the info box, then all the relative properties that that object in the array is populated back to the form.
Googling best tries for this, but not sure how I can work with the json objects this for for now. Can some of you help me on this?
Thanks much.
Hard to give the best way. Probably comes down to your style and preferences. But here is one way to do it, to get you going.
Define your model. It will contain the claim that is bound to the form and an array of added claims.
$scope.viewModel = {
claim: {},
claims: []
};
Add a function that assigns a claim object with default values:
var resetClaim = function() {
$scope.viewModel.claim = {
name: '',
city: ''
};
};
resetClaim();
The form elements will use ng-model:
<input type="text" model="viewModel.claim.name">
We will use ng-repeat to show the added claims:
<tr ng-repeat="claim in viewModel.claims">
Our form will have two buttons:
<button type="submit" ng-click="saveClaim()">Save Claim</button>
<button type="button" ng-click="cancel()">Cancel</button>
The cancel button will just reset the form.
The saveClaim function will look like this:
$scope.saveClaim = function() {
if (!isValidClaim()) return;
$scope.viewModel.claim.id ? updateClaim() : saveNewClaim();
resetClaim();
};
The isValidClaim function just checks if we have entered the requied fields. You could use form validation for this instead.
In this solution when saving a claim it could either be a new claim or an existing one that we have edited, and what we will do in the two cases will differ, so we need a way to tell what we are doing. Here we just check if it has an id. If it hasn't - it's a new claim. If it has, it's an existing.
To save a new claim we will do the following:
var saveNewClaim = function() {
var newClaim = angular.copy($scope.viewModel.claim);
newClaim.id = id++;
$scope.viewModel.claims.push(newClaim);
};
Note that it's important that we use for example angular.copy to create a new copy of the claim that is bound to the view. Otherwise we would just push a reference to the same object to the claims array which is not good since we want to reset one of them.
In this example id is just a variable starting at 0 that we increment each time we create a new claim.
Each element in our ng-repeat will have an edit and a remove icon:
<tr ng-repeat="claim in viewModel.claims">
<th>{{claim.id}}</th>
<td>{{claim.name}}</td>
<td>{{claim.city}}</td>
<td><i class="glyphicon glyphicon-edit" ng-click="editClaim(claim)"></i></td>
<td><i class="glyphicon glyphicon-remove" ng-click="removeClaim(claim)"></i></td>
</tr>
The removeClaim function simply takes a claim and removes it from the array:
$scope.removeClaim = function(claim) {
var index = $scope.viewModel.claims.indexOf(claim);
$scope.viewModel.claims.splice(index, 1);
};
The editClaim function will make a copy of the claim to edit and put it in the variable that is bound to the form:
$scope.editClaim = function(claim) {
$scope.viewModel.claim = angular.copy(claim);
};
You can also do the following:
$scope.viewModel.claim = claim;
And when you edit the claim in the form it will update in the ng-repeat at the same time. But then you have no good way of canceling and the save button wouldn't be needed. So it depends on how you want it to work.
If you edit the claim in the form now and save, we will come back to the saveClaim function:
$scope.saveClaim = function() {
if (!isValidClaim()) return;
$scope.viewModel.claim.id ? updateClaim() : saveNewClaim();
resetClaim();
};
This time the claim will have an id, so the updateClaim function will execute:
var updateClaim = function() {
var claim = $scope.viewModel.claims.filter(function(c) {
return c.id === $scope.viewModel.claim.id;
})[0];
angular.extend(claim, $scope.viewModel.claim);
};
It will retrieve the claim that we are editing from the claims array based on the id. We need to do this since we used angular.copy earlier and have two difference objects.
We will then use angular.extend to move all the new edited values to the claim that we pressed edit on in the ng-repeat.
Demo: http://plnkr.co/edit/yuNcZo7nUyxVsOyPTBEd?p=preview

$q.all(promises)and structure of promises object to collect the returned data

I am using Angularjs $q.all(promises) to make multiple REST call and then collecting the data once promise is successful. I have following following.
If "promises is simple array then it works Plunker
var promises = [
Users.query().$promise,
Repositories.query().$promise
];
If "promises" is simple object then also it works Plunker
var promises = {
users: Users.query().$promise,
repos: Repositories.query().$promise
};
If "promises" is nested object then it is not working. For my requirement I need nested object to remember the input parameters. Plunker
var promises = {
users: {"phx":Users.query().$promise},
repos: {"phx":Repositories.query().$promise}
};
These plunkr are just to simulate my problem. However I want this approach in real project for following requirement.
I have list of 12 product
Each product has "details", "benefits" and "offers" data
I have separate REST API services for "details", "benefits" and "offers" having :productID as parameter
I am making call in following order
a. Loop for each cards
b. For each card, make a REST API call for "details", "benefits" and "offers"
c. Add #b steps into "promises" object
d. call
$q.all(promises).then(function(results) {
// Here need logic to compile the result back to product
// and corresponding "details", "benefits" and "offers" mapping
}
and get the data back
Following is json structure I needed to collect my response.
{
"prod1": {
"benefits": {},
"offers": {},
"pages": {
"productPage": {}
}
}
},
"common": {
"benefits": {},
"pages": {
"commonBenefit": {}
},
"others": {}
}
How can I achieve this?
If you really need it, you can wrap the nest with $q.all like this:
var promises = {
users: $q.all({"phx": Users.query().$promise}),
repos: $q.all({"phx": Repositories.query().$promise})
};
plnkr.co

Unique array values in Mongoose

Currently trailing out Mongoose and MongoDB for a project of mine but come across a segment where the API is not clear.
I have a Model which contains several keys and documents, and one of those keys os called watchList. This is an array of ID's that the user is watching, But I need to be sure that these values stay unique.
Here is some sample code:
var MyObject = new Mongoose.Schema({
//....
watching : {type: Array, required: false},
//....
});
So my question is how can I make sure that the values pushed into the array only ever store one, so making the values unique, can i just use unique: true ?
Thanks
To my knowledge, the only way to do this in mongoose is to call the underlying Mongo operator (mentioned by danmactough). In mongoose, that'd look like:
var idToUpdate, theIdToAdd; /* set elsewhere */
Model.update({ _id: idToUpdate },
{ $addToSet: { theModelsArray: theIdToAdd } },
function(err) { /*...*/ }
);
Note: this functionality requires mongoose version >= 2.2.2
Take a look at the Mongo documentation on the $addToSet operator.
Mongoose is an object model for mongodb, so one option is to treat the document as a normal javascript object.
MyModel.exec(function (err, model) {
if(model.watching.indexOf(watchId) !== -1) model.watching.push(watchId);
model.save(...callback);
});
Although, I do agree that mongoose should have some support for this built in the form of a validator for the collection document reference feature-- especially because most of the time you want to add only unique references.
That's how you can do it using Mongoose,
IF your upcoming value is an Array
Model
.findOneAndUpdate({ _id: yourID },
{ $addToSet: { watching: { $each: yourWatchingArr } } },
function(err) { /*...*/ }
);
IF your upcoming value is a string
Model
.findOneAndUpdate({ _id: yourID },
{ $addToSet: { watching: yourStringValue } },
function(err) { /*...*/ }
);

Resources