import { Injectable , Injector } from '@angular/core' ; import { Observable } from "rxjs" ; import { flatMap , catchError , map } from "rxjs/operators" ; import { BaseResourceService } from "../../../shared/services/base-resource.service" ; import { CategoryService } from "../../categories/shared/category.service" ; import { Entry } from "./entry.model" ; import * as moment from "moment" ; @ Injectable ( { providedIn : 'root' } ) export class EntryService extends BaseResourceService < Entry > { constructor ( protected injector , private categoryService ) { super ( "api/entries" , injector , Entry . fromJson ) ; } create ( entry ) { return this . setCategoryAndSendToServer ( entry , super . create . bind ( this ) ) ; } update ( entry ) { return this . setCategoryAndSendToServer ( entry , super . update . bind ( this ) ) ; } getByMonthAndYear ( month , year ) { return this . getAll ( ) . pipe ( map ( entries => this . filterByMonthAndYear ( entries , month , year ) ) ) ; } private setCategoryAndSendToServer ( entry , sendFn ) { return this . categoryService . getById ( entry . categoryId ) . pipe ( flatMap ( category => { entry . category = category ; return sendFn ( entry ) ; } ) , catchError ( this . handleError ) ) ; } private filterByMonthAndYear ( entries , month , year ) { return entries . filter ( entry => { const entryDate = moment ( entry . date , "DD/MM/YYYY" ) ; const monthMatches = entryDate . month ( ) + 1 == month ; const yearMatches = entryDate . year ( ) == year ; if ( monthMatches && yearMatches ) return entry ; } ) ; } }