AzLearn

تمرين إعادة البناء

Typed Config Loader

أعد كتابة محمّل إعدادات TypeScript يتحقق من JSON قبل استخدامه.

typescript ~12 دقيقة مبتدئ
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
declare const process: {
  argv: string[];
};

type FileSystemModule = {
  existsSync(path: string): boolean;
  readFileSync(path: string, encoding: "utf8"): string;
};

declare function require(name: "fs"): FileSystemModule;

interface AppConfig {
  port: number;
  environment: "development" | "production";
  features: string[];
}

const fs = require("fs");

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null;
}

function parseConfig(value: unknown): AppConfig {
  if (!isRecord(value)) {
    throw new Error("Config must be an object");
  }

  if (typeof value.port !== "number") {
    throw new Error("Config port must be a number");
  }

  if (value.environment !== "development" && value.environment !== "production") {
    throw new Error("Config environment is invalid");
  }

  if (!Array.isArray(value.features) || !value.features.every((item) => typeof item === "string")) {
    throw new Error("Config features must be strings");
  }

  return {
    port: value.port,
    environment: value.environment,
    features: value.features,
  };
}

function loadConfig(path: string): AppConfig {
  if (!fs.existsSync(path)) {
    return { port: 3000, environment: "development", features: [] };
  }

  return parseConfig(JSON.parse(fs.readFileSync(path, "utf8")) as unknown);
}

const configPath = process.argv[2] ?? "app.config.json";
console.log(loadConfig(configPath));
اكتب هنا