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.
Code
// 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: protHow 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.