Skip to content

Commit

Permalink
fix: type safety
Browse files Browse the repository at this point in the history
coltenkrauter committed Dec 11, 2024

Verified

This commit was signed with the committer’s verified signature.
cjihrig Colin Ihrig
1 parent 296d36a commit 714b937
Showing 3 changed files with 15 additions and 10 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@krauters/environment",
"description": "A TypeScript utility library that provides a fluent, type-safe API for defining, transforming, and managing environment variable configurations in applications.",
"version": "0.5.0",
"version": "0.5.1",
"main": "dist/src/index.js",
"type": "commonjs",
"scripts": {
19 changes: 12 additions & 7 deletions src/environment.ts
Original file line number Diff line number Diff line change
@@ -79,26 +79,31 @@ export class EnvironmentBuilder<E = unknown, O = unknown> {
}

withPrefix(prefix: string): EnvironmentBuilder<E, O> {
console.info(`Using environment variable prefix [${prefix}]`)
debug(`Using environment variable prefix [${prefix}]`)

const exampleKeys = [...this.info.requiredKeys, ...this.info.optionalKeys]
const examples = exampleKeys.map((key) => `${prefix}${key.toUpperCase()}=example_value`)

if (examples.length > 0) {
console.info(`Example usage: [${examples.join(', ')}]`)
debug(`Example usage: [${examples.join(', ')}]`)
} else {
console.info(`Example usage: ${prefix}VARIABLE_NAME=example_value`)
debug(`Example usage: ${prefix}VARIABLE_NAME=example_value`)
}

const updatedInfo = { ...this.info, prefix }
const updatedInfo: EnvironmentInfo<E> = { ...this.info, prefix }

return new EnvironmentBuilder(updatedInfo)
}

private applyTransform(key: string, value: string | undefined): unknown {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
private applyTransform<T>(key: string, value: string | undefined): T | undefined {
const transformFunction = this.info.transforms[key]

return typeof transformFunction === 'function' && value ? transformFunction(value) : value
if (typeof transformFunction === 'function' && value !== undefined) {
return transformFunction(value) as T
}

return value as unknown as T | undefined
}

private prefixedKey(key: string): string {
@@ -139,7 +144,7 @@ export class EnvironmentBuilder<E = unknown, O = unknown> {
const finalValue = envValue ?? defaultValue

if (finalValue !== undefined) {
result.requiredValues[key as keyof E] = this.applyTransform(key, finalValue as string) as E[keyof E]
result.requiredValues[key as keyof E] = this.applyTransform(key, finalValue as string)
debug('Resolved required key', [key], 'value', [finalValue])
} else {
result.errors.push(key)

0 comments on commit 714b937

Please sign in to comment.