Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export enum LoadingStatus {
  2.     Loading = 1, Loaded = 2, Error = 3
  3. }
  4.  
  5.  
  6. export module LoadingStatus {
  7.     export function forHttpStatusCode(statusCode: number): LoadingStatus {
  8.         switch (statusCode) {
  9.             case 200:
  10.                 return LoadingStatus.Loaded;
  11.             case 202:
  12.                 return LoadingStatus.Loading;
  13.             default:
  14.                 return LoadingStatus.Error;
  15.         }
  16.     }
  17. }
  18.  
  19.  
  20. export class LoadableContent<T> {
  21.  
  22.     private readonly loadedTs: Date = null;
  23.  
  24.     private constructor(readonly status: LoadingStatus,
  25.                         readonly content: T) {
  26.         if (status === LoadingStatus.Loaded) {
  27.             this.loadedTs = new Date();
  28.         }
  29.     }
  30.  
  31.     static loading<T>(): LoadableContent<T> {
  32.         return new LoadableContent<T>(LoadingStatus.Loading, null);
  33.     }
  34.  
  35.     static loaded<T>(content: T): LoadableContent<T> {
  36.         return new LoadableContent<T>(LoadingStatus.Loaded, content);
  37.     }
  38.  
  39.     static failedToLoad<T>(): LoadableContent<T> {
  40.         return new LoadableContent<T>(LoadingStatus.Error, null);
  41.     }
  42.  
  43.     get loading() {
  44.         return this.status === LoadingStatus.Loading;
  45.     }
  46.  
  47.     get error() {
  48.         return this.status === LoadingStatus.Error;
  49.     }
  50.  
  51.     get loaded() {
  52.         return this.status === LoadingStatus.Loaded;
  53.     }
  54.  
  55.     fresh(ttlMs: number): boolean {
  56.         if (this.loadedTs === null) {
  57.             return false;
  58.         }
  59.  
  60.         const now = new Date();
  61.         const age = now.getTime() - this.loadedTs.getTime();
  62.         return age < ttlMs;
  63.     }
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement