Skip to content

Commit

Permalink
feat: stringFromSchemaEnv
Browse files Browse the repository at this point in the history
  • Loading branch information
holtwick committed Aug 27, 2024
1 parent 124c896 commit f0d9b8d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/common/schema/env.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { parseSchemaEnv } from './env'
import { parseSchemaEnv, stringFromSchemaEnv } from './env'
import { boolean, number, object, string } from './schema'

describe('env.spec', () => {
Expand Down Expand Up @@ -45,5 +45,11 @@ describe('env.spec', () => {
"servicePort": 9999,
}
`)

expect(stringFromSchemaEnv(schema, 'APP_', true)).toMatchInlineSnapshot(`
"# APP_SERVICE_NAME=generic
# APP_SERVICE_PORT=80
# APP_SERVICE_FLAG=true"
`)
})
})
14 changes: 13 additions & 1 deletion src/common/schema/env.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { assert } from '../assert'
import { objectFilter, objectMap, valueToBoolean, valueToBooleanNotFalse, valueToInteger } from '../data'
import { toCamelCase } from '../data/camelcase'
import { fromCamelCase, toCamelCase } from '../data/camelcase'
import type { Type } from './schema'
import { isSchemaObjectFlat } from './utils'

Expand Down Expand Up @@ -35,3 +35,15 @@ export function parseSchemaEnv<T>(schema: Type<T>, env: any = process?.env ?? {}
return schema.parse(value)
}) as T
}

export function stringFromSchemaEnv<T>(schema: Type<T>, prefix = '', commentOut = false): string {
assert(isSchemaObjectFlat(schema), 'schema should be a flat object')

const lines: string[] = []

objectMap(schema._object!, (key, schema) => {
lines.push(`${commentOut ? '# ' : ''}${prefix + fromCamelCase(key, '_').toUpperCase()}=${schema._default ?? ''}`)
}) as T

return lines.join('\n')
}

0 comments on commit f0d9b8d

Please sign in to comment.