Advertisement
Guest User

Untitled

a guest
Oct 6th, 2023
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 2.17 KB | Source Code | 0 0
  1. class Config {
  2.   private config: Record<string, any>;
  3.   private cache: Record<string, any>;
  4.  
  5.   constructor(config: Record<string, any>) {
  6.     this.config = config;
  7.     this.cache = {};
  8.   }
  9.  
  10.   getConfig() {
  11.     const getConfigRecursive = (target: Record<string, any>, path: string[]) => {
  12.       return new Proxy(target, {
  13.         get: (currentTarget, property) => {
  14.           const newPath = [...path, property.toString()];
  15.           const fullPath = newPath.join('.');
  16.  
  17.           if (fullPath in this.cache) {
  18.             console.log(`Getting ${fullPath} from cache`);
  19.             return this.cache[fullPath];
  20.           }
  21.  
  22.           if (typeof currentTarget[property] === 'object') {
  23.             return getConfigRecursive(currentTarget[property], newPath);
  24.           }
  25.  
  26.           console.log(`Getting ${fullPath} from config`);
  27.           const value = currentTarget[property];
  28.           this.cache[fullPath] = value;
  29.           return value;
  30.         },
  31.         set: (currentTarget, property, value) => {
  32.           const newPath = [...path, property.toString()];
  33.           const fullPath = newPath.join('.');
  34.           console.log(`Setting ${fullPath} in config`);
  35.           currentTarget[property] = value;
  36.           this.cache[fullPath] = value;
  37.           return true;
  38.         },
  39.       });
  40.     };
  41.  
  42.     return getConfigRecursive(this.config, []);
  43.   }
  44. }
  45.  
  46. const initialConfig = {
  47.   apiUrl: 'https://example.com/api',
  48.   apiKey: 'secret_key',
  49.   nested: {
  50.     nestedProperty: 'nested_value',
  51.   },
  52. };
  53.  
  54. const config = new Config(initialConfig).getConfig();
  55.  
  56. console.log(config.apiUrl); // Accessing apiUrl for the first time
  57. console.log(config.nested.nestedProperty); // Accessing nestedProperty for the first time
  58. console.log(config.apiUrl); // Accessing apiUrl from cache
  59. console.log(config.nested.nestedProperty); // Accessing nestedProperty from cache
  60. config.apiUrl = 'https://updated-api.com'; // Setting apiUrl in config
  61. config.nested.nestedProperty = 'new_nested_value'; // Setting nestedProperty in config
  62. console.log(config.apiUrl); // Accessing updated apiUrl from cache
  63. console.log(config.nested.nestedProperty); // Accessing updated nestedProperty from cache
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement