Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Config {
- private config: Record<string, any>;
- private cache: Record<string, any>;
- constructor(config: Record<string, any>) {
- this.config = config;
- this.cache = {};
- }
- getConfig() {
- const getConfigRecursive = (target: Record<string, any>, path: string[]) => {
- return new Proxy(target, {
- get: (currentTarget, property) => {
- const newPath = [...path, property.toString()];
- const fullPath = newPath.join('.');
- if (fullPath in this.cache) {
- console.log(`Getting ${fullPath} from cache`);
- return this.cache[fullPath];
- }
- if (typeof currentTarget[property] === 'object') {
- return getConfigRecursive(currentTarget[property], newPath);
- }
- console.log(`Getting ${fullPath} from config`);
- const value = currentTarget[property];
- this.cache[fullPath] = value;
- return value;
- },
- set: (currentTarget, property, value) => {
- const newPath = [...path, property.toString()];
- const fullPath = newPath.join('.');
- console.log(`Setting ${fullPath} in config`);
- currentTarget[property] = value;
- this.cache[fullPath] = value;
- return true;
- },
- });
- };
- return getConfigRecursive(this.config, []);
- }
- }
- const initialConfig = {
- apiUrl: 'https://example.com/api',
- apiKey: 'secret_key',
- nested: {
- nestedProperty: 'nested_value',
- },
- };
- const config = new Config(initialConfig).getConfig();
- console.log(config.apiUrl); // Accessing apiUrl for the first time
- console.log(config.nested.nestedProperty); // Accessing nestedProperty for the first time
- console.log(config.apiUrl); // Accessing apiUrl from cache
- console.log(config.nested.nestedProperty); // Accessing nestedProperty from cache
- config.apiUrl = 'https://updated-api.com'; // Setting apiUrl in config
- config.nested.nestedProperty = 'new_nested_value'; // Setting nestedProperty in config
- console.log(config.apiUrl); // Accessing updated apiUrl from cache
- console.log(config.nested.nestedProperty); // Accessing updated nestedProperty from cache
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement