import { Injectable } from "@angular/core" ; import { Storage } from "@ionic/storage" ; import _ from "lodash" ; import { Novel } from "../common/models/novel" ; import { NovelsLocalService } from "./novels-local-service" ; @ Injectable ( ) export class RecentNovelsService { recent = [ ] ; private RECENT : string = "recent" ; private MAX : number = 20 ; constructor ( private storage , private novelsLocalService ) { console . log ( "Hello RecentNovels Service" ) ; this . storage . get ( this . RECENT ) . then ( recent => this . recent = recent || [ ] ) . catch ( ( ) => { this . recent = [ ] ; } ) ; } get ( ) { return new Promise ( ( resolve , reject ) => { this . storage . get ( this . RECENT ) . then ( recent => { resolve ( recent || [ ] ) ; } ) . catch ( ( ) => { resolve ( [ ] ) ; } ) ; } ) ; } set ( recent ) { this . storage . set ( this . RECENT , recent ) ; } add ( novel ) { return new Promise ( ( resolve , reject ) => { this . get ( ) . then ( recents => { _ . pull ( recents , novel . id ) ; recents . unshift ( novel . id ) ; if ( recents . length > this . MAX ) { recents . pop ( ) ; } this . set ( recents ) ; this . novelsLocalService . add ( novel ) ; resolve ( ) ; } ) ; } ) ; } getNovels ( ) { console . log ( "RecentNovelsService::getNovels" ) ; return new Promise ( ( resolve ) => { this . get ( ) . then ( recent => { this . novelsLocalService . getNovels ( recent ) . then ( novels => { resolve ( novels ) ; } ) ; } ) . catch ( ( ) => { resolve ( [ ] ) ; } ) ; } ) ; } }