Skip to content

Commit

Permalink
Improved merge algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
FlorianRappl committed May 19, 2022
1 parent b633b8d commit 56b7725
Showing 1 changed file with 12 additions and 20 deletions.
32 changes: 12 additions & 20 deletions src/server/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,10 @@ export function readConfiguration(path: string): ConfigurationFile {
}

function mergeObjects<T>(
target: Partial<KrasConfiguration>,
sources: Array<Partial<KrasConfiguration>>,
select: (config: Partial<KrasConfiguration>) => Dict<T>,
) {
const obj = select(target);
const obj: Dict<T> = {};

for (const source of sources) {
const value = select(source);
Expand All @@ -94,15 +93,16 @@ function mergeObjects<T>(
});
}
}

return obj;
}

function mergeArrays<T>(
target: Partial<KrasConfiguration>,
sources: Array<Partial<KrasConfiguration>>,
select: (config: Partial<KrasConfiguration>) => Array<T>,
compare: (item1: T, item2: T) => boolean,
) {
const arr = select(target);
const arr: Array<T> = [];

for (const source of sources) {
const value = select(source);
Expand All @@ -121,21 +121,16 @@ function mergeArrays<T>(
arr.push(...value);
}
}

return arr;
}

export function mergeConfiguration(
options: ConfigurationOptions = {},
...configs: Array<ConfigurationFile>
): KrasConfiguration {
const { initial = {}, required = {} } = options;
const empty: Partial<KrasConfiguration> = {
map: {},
sources: [],
injectors: {},
middlewares: [],
injectorDirs: [],
};
const sources = [initial, ...configs, required, empty];
const sources = [initial, ...configs, required];
const result: KrasConfiguration = Object.assign({}, ...sources);

if (options.cert !== undefined || options.key !== undefined) {
Expand Down Expand Up @@ -165,22 +160,19 @@ export function mergeConfiguration(
result.port = options.port;
}

mergeObjects(result, sources, (m) => m.injectors);
mergeObjects(result, sources, (m) => m.map);
mergeArrays(
result,
result.injectors = mergeObjects(sources, (m) => m.injectors);
result.map = mergeObjects(sources, (m) => m.map);
result.sources = mergeArrays(
sources,
(m) => m.sources,
(a, b) => a === b,
);
mergeArrays(
result,
result.injectorDirs = mergeArrays(
sources,
(m) => m.injectorDirs,
(a, b) => a === b,
);
mergeArrays(
result,
result.middlewares = mergeArrays(
sources,
(m) => m.middlewares,
(a, b) => a.source === b.source,
Expand Down

0 comments on commit 56b7725

Please sign in to comment.