Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
CalebUsadi committed Dec 2, 2024
1 parent 05f1b87 commit 092eaec
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
3 changes: 3 additions & 0 deletions source/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export default class Conf<T extends Record<string, any> = Record<string, unknown
const schema: JSONSchema = {
type: 'object',
properties: options.schema,
...options.rootSchema,
};

this.#validator = ajv.compile(schema);
Expand All @@ -112,6 +113,8 @@ export default class Conf<T extends Record<string, any> = Record<string, unknown
this.#defaultValues[key as keyof T] = value.default; // eslint-disable-line @typescript-eslint/no-unsafe-assignment
}
}
} else if (options.rootSchema) {
throw new TypeError('`schema` option required to use `rootSchema`.');
}

if (options.defaults) {
Expand Down
7 changes: 7 additions & 0 deletions source/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ export type Options<T extends Record<string, any>> = {
*/
schema?: Schema<T>;

/**
Top-level properties for the schema.
Requires a `schema` option to be provided, and cannot contain a `properties` field.
*/
rootSchema?: Omit<TypedJSONSchema, 'properties'>;

/**
Name of the config file (without extension).
Expand Down
22 changes: 22 additions & 0 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -787,6 +787,28 @@ test('schema - validate Conf default', t => {
}, {message: 'Config schema violation: `foo` must be string'});
});

test('schema - rootSchema without schema', t => {
t.throws(() => {
new Conf({
cwd: temporaryDirectory(),
rootSchema: {},
});
}, {message: '`schema` option required to use `rootSchema`.'});
});

test('schema - validate rootSchema', t => {
t.throws(() => {
const config = new Conf({
cwd: temporaryDirectory(),
schema: {},
rootSchema: {
additionalProperties: false,
},
});
config.set('foo', 'bar');
}, {message: 'Config schema violation: `` must NOT have additional properties'});
});

test('.get() - without dot notation', t => {
t.is(t.context.configWithoutDotNotation.get('foo'), undefined);
t.is(t.context.configWithoutDotNotation.get('foo', '🐴'), '🐴');
Expand Down

0 comments on commit 092eaec

Please sign in to comment.