Function fromJSONFile

  • Asynchronously reads and validates JSON data from one or more files against a provided schema.

    This function allows for the loading of configuration or data from JSON files specified by path or paths. It handles reading multiple files in parallel, parses them as JSON, and then merges all objects into a single object to be validated against a given schema. Exception handling is integrated to manage and report errors effectively during file reading and parsing stages.

    Example


    import { fromJSONFile } from "@mrspartak/config";
    import * as z from "zod";

    const schema = z.object({
    environment: z.enum(["development", "production"]),
    port: z.number().default(3000),
    db: z.object({
    host: z.string(),
    port: z.number(),
    user: z.string(),
    password: z.string(),
    }),
    });

    const data = await fromJSONFile({
    path: ["config/default.json", "config/production.json"],
    schema,
    });

    console.log(data); // { environment: 'production', port: 3000, db: { host: 'localhost', port: 5432, user: 'admin', password: 'admin' } }
    const db = data.db; // Object { host: 'localhost', port: 5432, user: 'admin', password: 'admin' }

    Type Parameters

    Parameters

    • params: {
          path: string | string[];
          schema: $Validator;
      }

      The parameters object containing the path(s) and schema.

      • path: string | string[]

        Path or array of paths to JSON files that need to be read.

      • schema: $Validator

        The schema against which the data is validated after merging.

    Returns Promise<inferValidator<$Validator>["out"]>

    A promise that resolves with the validated data object.

    Throws

    • Throws an enhanced exception with contextual information if file reading or parsing fails.