Proxy Reflect Guard Config Access

Intercept config access with a Proxy: unknown keys throw on write to expose typos, reads fall back to defaults, and Reflect keeps base assignment intact.

JavascriptConfig Management

Code

javascriptsnippet
32 lines
// Proxy + Reflect: 读写拦截仍把基础行为委托给 Reflect,不重写语义
const defaults = { host: '127.0.0.1', port: 8080, retries: 3 };

function guardConfig(target) {
  const known = new Set([...Object.keys(defaults), ...Object.keys(target)]);
  return new Proxy(target, {
    get(obj, key) {
      if (!known.has(key)) return undefined; // 未声明键一律 undefined
      return obj[key] ?? defaults[key]; // 已声明但未赋值时回落默认值
    },
    set(obj, key, value) {
      if (!known.has(key)) {
        // 拼写错误即刻暴露,而不是静默写进一个无人读取的键
        throw new TypeError('unknown config key: ' + String(key));
      }
      return Reflect.set(obj, key, value); // 正常键交给 Reflect 完成赋值
    },
  });
}

const config = guardConfig({});

console.log('host   :', config.host);
console.log('missing:', config.timeout);
config.port = 9090;
console.log('port   :', config.port);

try {
  config.prot = 1234; // 拼写错误
} catch (error) {
  console.log('caught :', error.message);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

host   : 127.0.0.1
missing: undefined
port   : 9090
caught : unknown config key: prot

How it works

The part worth importing is the function guardConfig — everything else is wiring.

Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.

The result is a fresh construction, so callers can keep their originals.

Applying it

The main signature is written as function guardConfig(target)

Look for the host :, missing:, port : prefixes once the file starts running; each one ties a printed line to the step that produced it.

Statements that matter

return obj[key] ?? defaults[key]; // 已声明但未赋值时回落默认值
},
set(obj, key, value) {
if (!known.has(key)) {
// 拼写错误即刻暴露,而不是静默写进一个无人读取的键
throw new TypeError('unknown config key: ' + String(key));
}
const known = new Set([...Object.keys(defaults), ...Object.keys(target)]);
return Reflect.set(obj, key, value); // 正常键交给 Reflect 完成赋值
},
});

Interactive Tools for This Topic

FAQ

Does `guardConfig` modify its input?
It does not. Inputs are only read; the return value is freshly built.
How does the code behave when input is bad?
`TypeError` is raised at the guard, so invalid state never reaches the main logic.
Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `guardConfig` at load time.