Skip to content

Commit

Permalink
feat: create config dynamically (#809)
Browse files Browse the repository at this point in the history
  • Loading branch information
roman-sainchuk authored Aug 22, 2022
1 parent 96c33bf commit 8eaebe3
Show file tree
Hide file tree
Showing 3 changed files with 108 additions and 6 deletions.
80 changes: 79 additions & 1 deletion packages/core/src/config/__tests__/load.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { loadConfig, findConfig, getConfig } from '../load';
import { loadConfig, findConfig, getConfig, createConfig } from '../load';
import { RedoclyClient } from '../../redocly';
import { RuleConfig, RawConfig } from './../types';
import { Config } from '../config';

const fs = require('fs');
const path = require('path');
Expand Down Expand Up @@ -87,3 +89,79 @@ describe('getConfig', () => {
expect(getConfig()).toEqual(Promise.resolve({}));
});
});

describe('createConfig', () => {
it('should create config from string', async () => {
const config = await createConfig(`
styleguide:
extends:
- recommended
rules:
info-license: off
`);

verifyExtendedConfig(config, {
extendsRuleSet: 'recommended',
overridesRules: { 'info-license': 'off' },
});
});

it('should create config from object', async () => {
const rawConfig: RawConfig = {
styleguide: {
extends: ['minimal'],
rules: {
'info-license': 'off',
'tag-description': 'off',
'operation-2xx-response': 'off',
},
},
};
const config = await createConfig(rawConfig);

verifyExtendedConfig(config, {
extendsRuleSet: 'minimal',
overridesRules: rawConfig.styleguide!.rules as Record<string, RuleConfig>,
});
});
});

function verifyExtendedConfig(
config: Config,
{
extendsRuleSet,
overridesRules,
}: { extendsRuleSet: string; overridesRules: Record<string, RuleConfig> }
) {
const defaultPlugin = config.styleguide.plugins.find((plugin) => plugin.id === '');
expect(defaultPlugin).toBeDefined();

const recommendedRules = defaultPlugin?.configs?.[extendsRuleSet];
expect(recommendedRules).toBeDefined();

verifyOasRules(config.styleguide.rules.oas2, overridesRules, recommendedRules?.rules || {});
verifyOasRules(
config.styleguide.rules.oas3_0,
overridesRules,
Object.assign({}, recommendedRules?.rules, recommendedRules?.oas3_0Rules)
);
verifyOasRules(
config.styleguide.rules.oas3_1,
overridesRules,
Object.assign({}, recommendedRules?.rules, recommendedRules?.oas3_1Rules)
);
}

function verifyOasRules(
finalRuleset: Record<string, RuleConfig>,
overridesRules: Record<string, RuleConfig>,
defaultRuleset: Record<string, RuleConfig>
) {
Object.entries(finalRuleset).forEach(([ruleName, ruleValue]) => {
if (ruleName in overridesRules) {
expect(ruleValue).toBe(overridesRules[ruleName]);
} else {
expect(ruleValue).toBe(defaultRuleset[ruleName]);
}
});
}
33 changes: 28 additions & 5 deletions packages/core/src/config/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,24 @@ import * as fs from 'fs';
import * as path from 'path';
import { RedoclyClient } from '../redocly';
import { isEmptyObject, loadYaml, doesYamlFileExist } from '../utils';
import { parseYaml } from '../js-yaml';
import { Config, DOMAINS } from './config';
import { transformConfig } from './utils';
import { resolveConfig } from './config-resolvers';

import type { DeprecatedInRawConfig, RawConfig, Region } from './types';
import { RegionalTokenWithValidity } from '../redocly/redocly-client-types';

async function addConfigMetadata({
rawConfig,
customExtends,
configPath,
tokens,
}: {
rawConfig: RawConfig;
customExtends?: string[];
configPath?: string;
tokens?: RegionalTokenWithValidity[];
}): Promise<Config> {
if (customExtends !== undefined) {
rawConfig.styleguide = rawConfig.styleguide || {};
Expand All @@ -25,10 +29,7 @@ async function addConfigMetadata({
// rawConfig.styleguide = { extends: ['recommended'], recommendedFallback: true };
}

const redoclyClient = new RedoclyClient();
const tokens = await redoclyClient.getTokens();

if (tokens.length) {
if (tokens?.length) {
if (!rawConfig.resolve) rawConfig.resolve = {};
if (!rawConfig.resolve.http) rawConfig.resolve.http = {};
rawConfig.resolve.http.headers = [...(rawConfig.resolve.http.headers ?? [])];
Expand Down Expand Up @@ -69,10 +70,15 @@ export async function loadConfig(
if (typeof processRawConfig === 'function') {
await processRawConfig(rawConfig);
}
return await addConfigMetadata({

const redoclyClient = new RedoclyClient();
const tokens = await redoclyClient.getTokens();

return addConfigMetadata({
rawConfig,
customExtends,
configPath,
tokens,
});
}

Expand Down Expand Up @@ -102,3 +108,20 @@ export async function getConfig(configPath: string | undefined = findConfig()):
throw new Error(`Error parsing config file at '${configPath}': ${e.message}`);
}
}

type CreateConfigOptions = {
extends?: string[];
tokens?: RegionalTokenWithValidity[];
};

export async function createConfig(
config: string | RawConfig,
options?: CreateConfigOptions
): Promise<Config> {
return addConfigMetadata({
rawConfig: transformConfig(
typeof config === 'string' ? (parseYaml(config) as RawConfig) : config
),
...options,
});
}
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export {
findConfig,
CONFIG_FILE_NAMES,
RuleSeverity,
createConfig,
} from './config';

export { RedoclyClient, isRedoclyRegistryURL } from './redocly';
Expand Down

1 comment on commit 8eaebe3

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage report

St.
Category Percentage Covered / Total
🟡 Statements 68.74% 2894/4210
🟡 Branches 62.01% 1601/2582
🟡 Functions 60.1% 464/772
🟡 Lines 68.58% 2682/3911

Test suite run success

461 tests passing in 76 suites.

Report generated by 🧪jest coverage report action from 8eaebe3

Please sign in to comment.