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 using the defineConfigParser
utility function.
Its API is minimal and straightforward:
import { defineConfigParser } from "@layerfig/config";
export const customParser = defineConfigParser({ acceptedFileExtensions: ["ini"], parse: (fileContent) => { // Logic to fetch, read, and parse the content },});
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 } from "@layerfig/config";import { customParser } 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: customParser,}) .addSource("base.ini") .addSource("live.ini") .build();