Skip to content

Commit 29d4562

Browse files
committed
refactor: migrate config loader to Zod
1 parent 80f2736 commit 29d4562

1 file changed

Lines changed: 29 additions & 13 deletions

File tree

src/config/file.ts

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,43 @@
11
import { readFileSync } from 'fs';
22
import { join } from 'path';
3-
import { validate as jsonSchemaValidate } from 'jsonschema';
3+
import { ConfigSchema, type Config } from '../../proxy.config.schema';
44

5-
export let configFile: string = join(process.cwd(), 'proxy.config.json');
5+
export let configFile: string = join(process.cwd(), 'config.proxy.json');
6+
export let config: Config;
67

78
/**
8-
* Set the config file path.
9-
* @param {string} file - The path to the config file.
9+
* Sets the path to the configuration file.
10+
*
11+
* @param {string} file - The path to the configuration file.
12+
* @return {void}
1013
*/
1114
export function setConfigFile(file: string) {
1215
configFile = file;
1316
}
1417

1518
/**
16-
* Validate config file.
17-
* @param {string} configFilePath - The path to the config file.
18-
* @return {boolean} - Returns true if validation is successful.
19-
* @throws Will throw an error if the validation fails.
19+
* Loads and validates the configuration file using Zod.
20+
* If validation succeeds, the parsed config is stored in the exported `config`.
21+
*
22+
* @return {Config} The validated and default-filled configuration object.
23+
* @throws {ZodError} If validation fails.
2024
*/
21-
export function validate(configFilePath: string = configFile!): boolean {
22-
const config = JSON.parse(readFileSync(configFilePath, 'utf-8'));
23-
const schemaPath = join(process.cwd(), 'config.schema.json');
24-
const schema = JSON.parse(readFileSync(schemaPath, 'utf-8'));
25-
jsonSchemaValidate(config, schema, { required: true, throwError: true });
25+
export function loadConfig(): Config {
26+
const raw = JSON.parse(readFileSync(configFile, 'utf-8'));
27+
const parsed = ConfigSchema.parse(raw);
28+
config = parsed;
29+
return parsed;
30+
}
31+
32+
/**
33+
* Validates a configuration file without mutating the exported `config`.
34+
*
35+
* @param {string} [filePath=configFile] - Path to the configuration file to validate.
36+
* @return {boolean} Returns `true` if the file passes validation.
37+
* @throws {ZodError} If validation fails.
38+
*/
39+
export function validate(filePath: string = configFile): boolean {
40+
const raw = JSON.parse(readFileSync(filePath, 'utf-8'));
41+
ConfigSchema.parse(raw);
2642
return true;
2743
}

0 commit comments

Comments
 (0)