Merge pull request #1363 from spotify/rugvip/confctx

packages/config: add context to config to display better errors messages
This commit is contained in:
Patrik Oldsberg
2020-06-18 10:36:21 +02:00
committed by GitHub
9 changed files with 191 additions and 60 deletions
+6 -3
View File
@@ -45,9 +45,12 @@ describe('readEnv', () => {
}),
).toEqual([
{
foo: 'bar',
numbers: { a: 1, b: 2, c: false },
very: { deep: { nested: { config: { object: {} } } } },
data: {
foo: 'bar',
numbers: { a: 1, b: 2, c: false },
very: { deep: { nested: { config: { object: {} } } } },
},
context: 'env',
},
]);
});
+3 -3
View File
@@ -42,7 +42,7 @@ const CONFIG_KEY_PART_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z][a-z0-9]*)*$/i;
export function readEnv(env: {
[name: string]: string | undefined;
}): AppConfig[] {
let config: JsonObject | undefined = undefined;
let data: JsonObject | undefined = undefined;
for (const [name, value] of Object.entries(env)) {
if (!value) {
@@ -52,7 +52,7 @@ export function readEnv(env: {
const key = name.replace(ENV_PREFIX, '');
const keyParts = key.split('_');
let obj = (config = config ?? {});
let obj = (data = data ?? {});
for (const [index, part] of keyParts.entries()) {
if (!CONFIG_KEY_PART_PATTERN.test(part)) {
throw new TypeError(`Invalid env config key '${key}'`);
@@ -87,5 +87,5 @@ export function readEnv(env: {
}
}
return config ? [config] : [];
return data ? [{ data, context: 'env' }] : [];
}
+11 -5
View File
@@ -38,11 +38,14 @@ describe('readConfigFile', () => {
} as ReaderContext);
await expect(config).resolves.toEqual({
app: {
title: 'Test',
x: 1,
y: [true],
data: {
app: {
title: 'Test',
x: 1,
y: [true],
},
},
context: 'app-config.yaml',
});
});
@@ -83,7 +86,10 @@ describe('readConfigFile', () => {
});
await expect(config).resolves.toEqual({
app: 'secret',
data: {
app: 'secret',
},
context: 'app-config.yaml',
});
expect(readSecret).toHaveBeenCalledWith({ file: './my-secret' });
});
+7 -3
View File
@@ -15,15 +15,19 @@
*/
import yaml from 'yaml';
import { basename } from 'path';
import { isObject } from './utils';
import { JsonValue, JsonObject } from '@backstage/config';
import { JsonValue, JsonObject, AppConfig } from '@backstage/config';
import { ReaderContext } from './types';
/**
* Reads and parses, and validates, and transforms a single config file.
* The transformation rewrites any special values, like the $secret key.
*/
export async function readConfigFile(filePath: string, ctx: ReaderContext) {
export async function readConfigFile(
filePath: string,
ctx: ReaderContext,
): Promise<AppConfig> {
const configYaml = await ctx.readFile(filePath);
const config = yaml.parse(configYaml);
@@ -76,5 +80,5 @@ export async function readConfigFile(filePath: string, ctx: ReaderContext) {
if (!isObject(finalConfig)) {
throw new TypeError('Expected object at config root');
}
return finalConfig;
return { data: finalConfig, context: basename(filePath) };
}