Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/config scope json support #94

Merged
merged 6 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
"dependencies": {
"pino": "^8.17.1",
"undici": "^6.0.1",
"undici-retry": "^5.0.2"
"undici-retry": "^5.0.2",
"zod": "^3.22.4"
},
"devDependencies": {
"@types/node": "^20.10.4",
Expand All @@ -53,7 +54,6 @@
"prettier": "^3.1.1",
"typescript": "^5.3.3",
"vitest": "^0.34.6",
"zod": "^3.22.4",
"vite": "4.5.0"
}
}
198 changes: 198 additions & 0 deletions src/config/ConfigScope.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { expect } from 'vitest'
import { z } from 'zod'

import { ConfigScope } from './ConfigScope'
import { ensureClosingSlashTransformer } from './configTransformers'
import type { EnvValueValidator } from './configTypes'
Expand Down Expand Up @@ -600,6 +603,201 @@ describe('ConfigScope', () => {
})
})

describe('getMandatoryJsonObject', () => {
it('empty env value throws error', () => {
const configScope = new ConfigScope()
const schema = z.object({ a: z.string() })

expect(() => configScope.getMandatoryJsonObject('emptyObjectValue', schema)).toThrow(
/Missing mandatory configuration parameter/,
)
})

it('env value not meeting schema throws error', () => {
process.env.objectValue = JSON.stringify({ b: 1 })
const configScope = new ConfigScope()

const schema = z.object({ a: z.string() })
expect(() => configScope.getMandatoryJsonObject('objectValue', schema)).toThrow(
/Configuration parameter objectValue must be a valid JSON meeting the given schema, but was {"b":1}/,
)
})

it('transform simple objects', () => {
process.env.objectValue = JSON.stringify({ a: 'a', b: 1 })
const configScope = new ConfigScope()

const schema = z.object({
a: z.string(),
b: z.number(),
})
const result = configScope.getMandatoryJsonObject('objectValue', schema)

expect(result).toEqual({ a: 'a', b: 1 })
})

it('transform array', () => {
process.env.objectValue = JSON.stringify([
{ a: 'a1', b: 1 },
{ a: 'a2', b: 2 },
])
const configScope = new ConfigScope()

const schema = z.array(
z.object({
a: z.string(),
b: z.number(),
}),
)
const result = configScope.getMandatoryJsonObject('objectValue', schema)

expect(result).toEqual([
{ a: 'a1', b: 1 },
{ a: 'a2', b: 2 },
])
})
})

describe('getOptionalJsonObject', () => {
it('empty env value returns default', () => {
const configScope = new ConfigScope()
const schema = z.object({ a: z.string() })

const result = configScope.getOptionalJsonObject('emptyObjectValue', schema, { a: 'a' })
expect(result).toEqual({ a: 'a' })
})

it('env value not meeting schema throws error', () => {
process.env.objectValue = JSON.stringify({ b: 1 })
const configScope = new ConfigScope()

const schema = z.object({ a: z.string() })

expect(() => configScope.getOptionalJsonObject('objectValue', schema, { a: 'a' })).toThrow(
/Configuration parameter objectValue must be a valid JSON meeting the given schema, but was {"b":1}/,
)
})

it('transform simple objects', () => {
process.env.objectValue = JSON.stringify({ a: 'a', b: 1 })
const configScope = new ConfigScope()

const schema = z.object({
a: z.string(),
b: z.number(),
})
const result = configScope.getOptionalJsonObject('objectValue', schema, { a: 'fake', b: -1 })

expect(result).toMatchObject({ a: 'a', b: 1 })
})

it('transform array', () => {
process.env.objectValue = JSON.stringify([
{ a: 'a1', b: 1 },
{ a: 'a2', b: 2 },
])
const configScope = new ConfigScope()

const schema = z.array(
z.object({
a: z.string(),
b: z.number(),
}),
)
const result = configScope.getOptionalJsonObject('objectValue', schema, [
{ a: 'fake', b: -1 },
])

expect(result).toMatchObject([
{ a: 'a1', b: 1 },
{ a: 'a2', b: 2 },
])
})
})

describe('getOptionalNullableJsonObject', () => {
it('empty env value returns default', () => {
const configScope = new ConfigScope()
const schema = z.object({ a: z.string() })

const result = configScope.getOptionalNullableJsonObject(
'emptyObjectValue',
schema,
undefined,
)
expect(result).toEqual(undefined)

const result2 = configScope.getOptionalNullableJsonObject('emptyObjectValue', schema, null)
expect(result2).toEqual(null)

const result3 = configScope.getOptionalNullableJsonObject('emptyObjectValue', schema, {
a: 'a',
})
expect(result3).toEqual({ a: 'a' })
})

it('env value not meeting schema returns default', () => {
process.env.objectValue = JSON.stringify({ b: 1 })
const configScope = new ConfigScope()
const schema = z.object({ a: z.string() })

expect(() =>
configScope.getOptionalNullableJsonObject('objectValue', schema, { a: 'a' }),
).toThrow(
/Configuration parameter objectValue must be a valid JSON meeting the given schema, but was {"b":1}/,
)

expect(() => configScope.getOptionalNullableJsonObject('objectValue', schema, null)).toThrow(
/Configuration parameter objectValue must be a valid JSON meeting the given schema, but was {"b":1}/,
)

expect(() =>
configScope.getOptionalNullableJsonObject('objectValue', schema, undefined),
).toThrow(
/Configuration parameter objectValue must be a valid JSON meeting the given schema, but was {"b":1}/,
)
})

it('transform simple objects', () => {
process.env.objectValue = JSON.stringify({ a: 'a', b: 1 })
const configScope = new ConfigScope()

const schema = z.object({
a: z.string(),
b: z.number(),
})
const result = configScope.getOptionalNullableJsonObject('objectValue', schema, {
a: 'fake',
b: -1,
})

expect(result).toMatchObject({ a: 'a', b: 1 })
})

it('transform array', () => {
process.env.objectValue = JSON.stringify([
{ a: 'a1', b: 1 },
{ a: 'a2', b: 2 },
])
const configScope = new ConfigScope()

const schema = z.array(
z.object({
a: z.string(),
b: z.number(),
}),
)
const result = configScope.getOptionalNullableJsonObject('objectValue', schema, [
{ a: 'fake', b: -1 },
])

expect(result).toMatchObject([
{ a: 'a1', b: 1 },
{ a: 'a2', b: 2 },
])
})
})

describe('updateEnv', () => {
it('updates cached env', () => {
process.env.value = '123'
Expand Down
49 changes: 49 additions & 0 deletions src/config/ConfigScope.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { ZodSchema } from 'zod'

import { InternalError } from '../errors/InternalError'

import type { EnvValueValidator } from './configTypes'
Expand Down Expand Up @@ -180,6 +182,36 @@ export class ConfigScope {
return rawValue === 'true'
}

getMandatoryJsonObject<T extends object>(param: string, schema: ZodSchema<T>): T {
const rawValue = this.getMandatory(param)
return this.validateSchema(
JSON.parse(rawValue),
schema,
`Configuration parameter ${param} must be a valid JSON meeting the given schema, but was ${rawValue}`,
)
}

getOptionalNullableJsonObject<T extends object, Z extends T | null | undefined>(
param: string,
schema: ZodSchema<T>,
defaultValue: Z,
): Z {
const rawValue = this.getOptionalNullable(param, undefined)
if (!rawValue) {
return defaultValue
}

return this.validateSchema(
JSON.parse(rawValue),
schema,
`Configuration parameter ${param} must be a valid JSON meeting the given schema, but was ${rawValue}`,
) as Z
}

getOptionalJsonObject<T extends object>(param: string, schema: ZodSchema<T>, defaultValue: T): T {
return this.getOptionalNullableJsonObject(param, schema, defaultValue)
}

isProduction(): boolean {
return this.env.NODE_ENV === 'production'
}
Expand All @@ -191,6 +223,23 @@ export class ConfigScope {
isTest(): boolean {
return this.env.NODE_ENV === 'test'
}

private validateSchema<T extends object>(
value: unknown,
schema: ZodSchema<T>,
errorMessage: string,
): T {
const parsedValue = schema.safeParse(value)
if (!parsedValue.success) {
throw new InternalError({
message: errorMessage,
errorCode: 'CONFIGURATION_ERROR',
details: parsedValue.error,
})
}

return parsedValue.data
}
}

export function validateOneOf<const T>(
Expand Down