Skip to content
GitHub

Custom Parser

The library provides abstractions to support common configuration file extensions. However, you may need to parse a file type that isn’t supported out-of-the-box.

To do so, you can write a custom parser extending the ConfigParser abstracted class:

// ./path/to/custom-parser.ts
import { ConfigParser } from "@layerfig/config";

class IniParser extends ConfigParser {
  constructor() {
    super({
      acceptedFileExtensions: ["ini"],
    });
  }

  load(fileContent: string) {
    // Logic to fetch, read, and parse the content
    // should return a Result
  }
}

export const iniParser = new InitParser();

The parse function must return an object that conforms to the Result type:

const successResult = {
  ok: true,
  data: {}, // The object containing your parsed configuration
};

const errorResult = {
  ok: false,
  error: new Error("Some error"), // The error that occurred
};

Then, use your custom parser by passing it to the ConfigBuilder:

import { ConfigBuilder, FileSource } from "@layerfig/config";
import { iniParser } from "./path/to/custom-parser";

export const config = new ConfigBuilder({
  validate: (finalConfig, z) => {
    const schema = z.object({
      appURL: z.url(),
      port: z.number(),
    });

    return schema.parse(finalConfig);
  },
  parser: iniParser,
})
  .addSource(new FileSource("base.ini"))
  .addSource(new FileSource("live.ini"))
  .build();