I've been experimenting with feathersjs and angular2/Rx. What I'm trying to achieve is building an angular2 service that's wrapping a feathersjs service in such a way that one can just subscribe to an Observable that emits an up-to-date set of items after any kind of CRUD.
It basically works. However, I don't find the way it's done very elegant: Wrapping and unwrapping every object that's coming in doesn't seem efficient. Am I taking 'Everything's a stream' too far?
getService(){
let data$: Observable<any> = Observable.from([initialSetOfItems]);
let created$: Observable<any> = Observable.fromEvent(feathersService, 'created').map(o => {return {action: 'c', data: o}});
let updated$: Observable<any> = Observable.fromEvent(feathersService, 'updated').map(o => {return {action: 'u', data: o}});
let removed$: Observable<any> = Observable.fromEvent(feathersService, 'removed').map(o => {return {action: 'r', data: o}});
return data$
.merge(created$, updated$, removed$)
.scan((arr: any[], newObj) => {
switch (newObj.action){
case 'c':
return [].concat(arr, newObj.data);
case 'u':
let indexToUpdate = arr.findIndex((element) => (element.id === newObj.data.id));
if (indexToUpdate > -1){
arr[indexToUpdate] = newObj.data;
}
return arr;
case 'r':
return arr.filter(element => (element.id != newObj.data.id))
}
});
}
I know this might be opinionated. Please bear with me. Rx is a little hard to wrap your head around.
How would you guys try to achieve this?