Created
June 16, 2017 09:12
-
-
Save dvitiuk-opensource/93fcfa4d3d6917be94b438d44c7985ae to your computer and use it in GitHub Desktop.
features
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, isDevMode, NgModule, Pipe } from "@angular/core"; | |
import { Observable } from "rxjs/Observable"; | |
import { BehaviorSubject } from "rxjs/BehaviorSubject"; | |
export type AvailableFeatures = keyof { "FEATURE_FROM_BACK", "PAID_PLAN": false } | |
export type AvailableFeaturesObj = {[key in AvailableFeatures]: any}; | |
export const Features: AvailableFeaturesObj = { | |
"PAID_PLAN": true, | |
} | |
@Injectable() | |
export class FeaturesService { | |
constructor(private httpClient: HttpClient, private user: User) { | |
this.updateQuotes(); | |
this.user.status$.subscribe(loggedId => { | |
if (!loggedId) { | |
this.featuresCache.next(Features); | |
} | |
}) | |
} | |
private featuresCache = new BehaviorSubject<AvailableFeaturesObj>(Features); | |
updateQuotes() { | |
this.httpClient.get(`api/users/quotas`).subscribe(res => { | |
if (isDevMode()) { | |
console.assert(JSON.stringify(Object.keys(Features)) === JSON.stringify(Object.keys(res)), `FeaturesService: go check check available features`); | |
} | |
this.featuresCache.next(res); | |
}); | |
} | |
isFeatureAvailable(feature: AvailableFeatures): Observable<number> { | |
return this.featuresCache.map(res => res && res[feature]); | |
} | |
} | |
@Pipe({ | |
name: 'isAvailableFeature', | |
pure: false, | |
}) | |
export class IsAvailableFeaturePipe { | |
constructor(private service: FeaturesService) { | |
} | |
transform(featureName: AvailableFeatures) { | |
return this.service.isFeatureAvailable(featureName); | |
} | |
} | |
@NgModule({ | |
imports: [], | |
declarations: [IsAvailableFeaturePipe], | |
exports: [IsAvailableFeaturePipe], | |
}) | |
export class FeaturesModule { | |
static forRoot() { | |
return { | |
ngModule: FeaturesModule, | |
providers: [FeaturesService], | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment