I have an events database maintained in Firestore. I use AngularFire5 to keep the events synced to my app.
The events have many 'sessions', that can be updated my multiple administrators and users(ratings, questions etc).
I'm using ngrx store, reducers and effects to maintain the sync. I was able to figure out the single session update/delete/add.
The issue is that the initial load of sessions returns a session[]. And beyond that, the snapshot changes could return 'added', 'modified' and 'removed' session. How can I use a single action+reducer function to add when session(s) is not existing, but update or remove when session(s) existing. (I'm not calling store.dispatch within my firebase service, I'm using the effects to manage this)
session.effect.ts
@Effect()
getSession: Observable<Action> = this.actions.ofType(SessionActions.ADD_SESSION)
.map((action: SessionActions.AddSession) => action.payload)
.switchMap(payload => this.db.getSessions(payload)
.map((sessions:Session[]) => new SessionActions.AddSessionSuccess(sessions))
);
session.reducer.ts
export function SessionReducer(state: Session[], action: Action) {
// console.log('SessionsReducer :: Action Type: ' + action.type + ', Action Payload: ' + JSON.stringify(action.payload));
switch(action.type) {
case SessionActions.ADD_SESSION_SUCCESS:
return [ ...state, action.payload ];
case SessionActions.CREATE_SESSION_SUCCESS:
return [ ...state, action.payload ];
case SessionActions.UPDATE_SESSION_SUCCESS:
return state.map(session => {
return session.id === action.payload.id ? Object.assign({}, action.payload) : session;
})
case SessionActions.ADD_SESSION:
case SessionActions.DELETE_SESSION_FAILURE:
return state;
default:
return state;
}
}
session.actions.ts
//Used to search the sessions by event id, think of it as GetSessions
export class AddSession implements Action {
readonly type = ADD_SESSION;
constructor(public payload: string) {}
}
export class AddSessionSuccess implements Action {
readonly type = ADD_SESSION_SUCCESS;
constructor(public payload: Session[]) {}
}