Search code examples
angulartypescriptionic2constantsionic3

Typescript class which has only the constants


I would like to keep my cache keys in a central place.I would like to do it as a constant file.At this moment I have declared cache keys each and every page where it's required.But I need to remove that duplication.How can I do that?

One of cache key declaration:

purchasedOfflineArticlesKey: string = 'myLibraryPurchasedOfflineArticles';

Can you tell me a proper design for this? Do I need to create a class for this and use that class in other places where it needs or any other way? Hope you'll give feedback for this.

Update:

I have cache service like below.

local-cache-service.ts

import { Injectable } from '@angular/core';
import { CacheService } from "ionic-cache";

@Injectable()
export class LocalCacheServiceProvider {

  constructor(private cache: CacheService) { }

  //get Item
  getItem(key: string): Promise<any> {
    return this.cache.getItem(key);
  }
}

I have used it like this:

offline-articles.ts

private purchasedOfflineArticlesKey: string = 'myLibraryPurchasedOfflineArticles';

 constructor(private localCacheService: LocalCacheServiceProvider) {
  }

     ionViewDidLoad() {
        this.localCacheService.getItem(this.purchasedOfflineArticlesKey).then(values => {
          this.arrangeMyOfflineArticles(values);
        }).catch(reason => {
        });
      }

Solution

  • Classes shouldn't be used for something that cannot benefit from class instantiation.

    One option is to have them as exports in separate file, this way non-existent keys can be resolved on import:

    export const foo = 'foo';
    export const bar = 'bar';
    

    Alternatively, cache keys can be declared as object keys, e.g. in the place where cache service is declared.

    export const CACHE_KEYS = {
        foo: 'foo',
        bar: 'bar'
    };
    
    @Injectable()
    export class LocalCacheServiceProvider {
      constructor(private cache: CacheService) { }
    
      getItem(key: keyof typeof CACHE_KEYS): Promise<any> {
        return this.cache.getItem(key);
      }
    }
    

    The service can make use of keyof constraint to limit the keys to known ones.

    Depending on the design of the application, LocalCacheServiceProvider and key set can be extended per module/component to provide unique set of keys for the unit.