Skip to content

Commit

Permalink
Convert addRating to use observables
Browse files Browse the repository at this point in the history
  • Loading branch information
paulbert committed Dec 26, 2017
1 parent fb354cc commit 158a70b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 17 deletions.
34 changes: 18 additions & 16 deletions src/app/resources/rate-resources/resources-rate.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { UserService } from '../../shared/user.service';
import { findDocuments } from '../../shared/mangoQueries';

import { ActivatedRoute, ParamMap, Router } from '@angular/router';
import { switchMap } from 'rxjs/operators';

import {
FormBuilder,
Expand Down Expand Up @@ -48,28 +49,29 @@ export class ResourcesRateComponent implements OnInit {
this.addRating(this.ratingForm.value);
}

async addRating(ratingInfo) {
try {
const result = await this.couchService.post(this.ratingDb + '/_find', findDocuments({
// Selector
'user.name': this.addInfo.user.name,
'parentId': this.addInfo.parentId
},
// Fields
[ '_id', '_rev' ]
));
getExistingRating() {
return this.couchService.post(this.ratingDb + '/_find', findDocuments({
// Selector
'user.name': this.addInfo.user.name,
'parentId': this.addInfo.parentId
},
// Fields
[ '_id', '_rev' ]
));
}

addRating(ratingInfo) {
this.getExistingRating().pipe(switchMap((result: any) => {
const uploadDoc = { ...ratingInfo, ...this.addInfo, type: 'resource' };
if (result.docs.length === 0) {
await this.couchService.post(this.ratingDb, uploadDoc);
return this.couchService.post(this.ratingDb, uploadDoc);
} else {
const docInfo = result.docs[0];
await this.couchService.put(this.ratingDb + '/' + docInfo._id + '?rev=' + docInfo._rev, uploadDoc);
return this.couchService.put(this.ratingDb + '/' + docInfo._id + '?rev=' + docInfo._rev, uploadDoc);
}
})).subscribe(res => {
this.router.navigate([ '/resources' ]);
} catch (err) {
// Connect to an error display component to show user that an error has occurred
console.log(err);
}
}, err => console.log(err));
}

}
2 changes: 1 addition & 1 deletion src/app/resources/resources.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export class ResourcesComponent implements OnInit, AfterViewInit {
// If there's an error, return a fake couchDB empty response
// so resources can be displayed.
return of({ docs: [] });
}
}));
}

addRatingToResource = (id, index, ratings, ratingInfo) => {
Expand Down

0 comments on commit 158a70b

Please sign in to comment.