Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export enum LoadingStatus {
- Loading = 1, Loaded = 2, Error = 3
- }
- export module LoadingStatus {
- export function forHttpStatusCode(statusCode: number): LoadingStatus {
- switch (statusCode) {
- case 200:
- return LoadingStatus.Loaded;
- case 202:
- return LoadingStatus.Loading;
- default:
- return LoadingStatus.Error;
- }
- }
- }
- export class LoadableContent<T> {
- private readonly loadedTs: Date = null;
- private constructor(readonly status: LoadingStatus,
- readonly content: T) {
- if (status === LoadingStatus.Loaded) {
- this.loadedTs = new Date();
- }
- }
- static loading<T>(): LoadableContent<T> {
- return new LoadableContent<T>(LoadingStatus.Loading, null);
- }
- static loaded<T>(content: T): LoadableContent<T> {
- return new LoadableContent<T>(LoadingStatus.Loaded, content);
- }
- static failedToLoad<T>(): LoadableContent<T> {
- return new LoadableContent<T>(LoadingStatus.Error, null);
- }
- get loading() {
- return this.status === LoadingStatus.Loading;
- }
- get error() {
- return this.status === LoadingStatus.Error;
- }
- get loaded() {
- return this.status === LoadingStatus.Loaded;
- }
- fresh(ttlMs: number): boolean {
- if (this.loadedTs === null) {
- return false;
- }
- const now = new Date();
- const age = now.getTime() - this.loadedTs.getTime();
- return age < ttlMs;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement