1
0
Fork 0

lint: extract common rule source logic from file/module helpers

This commit is contained in:
ssube 2019-11-17 18:43:25 -06:00 committed by Sean Sube
parent 61498e7fab
commit 7fce9649ec
1 changed files with 24 additions and 13 deletions

View File

@ -74,7 +74,7 @@ export interface RuleSourceData {
export interface RuleSourceModule { export interface RuleSourceModule {
definitions?: Dictionary<any>; definitions?: Dictionary<any>;
name: string; name: string;
rules: Array<Rule>; rules: Array<Rule | RuleData>;
} }
export function createRuleSelector(options: Partial<RuleSelector>): RuleSelector { export function createRuleSelector(options: Partial<RuleSelector>): RuleSelector {
@ -96,6 +96,25 @@ export function createRuleSources(options: Partial<RuleSources>): RuleSources {
}; };
} }
export function isPOJSO(val: any): val is RuleData {
const pojsoProto = Reflect.getPrototypeOf({});
return Reflect.getPrototypeOf(val) === pojsoProto;
}
export async function loadRuleSource(data: RuleSourceData | RuleSourceModule, ctx: VisitorContext): Promise<Array<Rule>> {
if (doesExist(data.definitions)) {
ctx.addSchema(data.name, data.definitions);
}
return Array.from(data.rules).map((it: Rule | RuleData) => {
if (isPOJSO(it)) {
return new SchemaRule(it);
} else {
return it;
}
});
}
export async function loadRuleFiles(paths: Array<string>, ctx: VisitorContext): Promise<Array<Rule>> { export async function loadRuleFiles(paths: Array<string>, ctx: VisitorContext): Promise<Array<Rule>> {
const parser = new YamlParser(); const parser = new YamlParser();
const rules = []; const rules = [];
@ -116,11 +135,7 @@ export async function loadRuleFiles(paths: Array<string>, ctx: VisitorContext):
continue; continue;
} }
if (doesExist(data.definitions)) { rules.push(...await loadRuleSource(data, ctx));
ctx.addSchema(data.name, data.definitions);
}
rules.push(...data.rules.map((it: RuleData) => new SchemaRule(it)));
} }
} }
@ -155,19 +170,15 @@ export async function loadRuleModules(modules: Array<string>, ctx: VisitorContex
for (const name of modules) { for (const name of modules) {
try { try {
/* eslint-disable-next-line @typescript-eslint/no-var-requires */ /* eslint-disable-next-line @typescript-eslint/no-var-requires */
const module: RuleSourceModule = r(name); const data: RuleSourceModule = r(name);
if (!validateRules(ctx, module)) { if (!validateRules(ctx, data)) {
ctx.logger.error({ ctx.logger.error({
module: name, module: name,
}, 'error loading rule module'); }, 'error loading rule module');
continue; continue;
} }
if (doesExist(module.definitions)) { rules.push(...await loadRuleSource(data, ctx));
ctx.addSchema(module.name, module.definitions);
}
rules.push(...module.rules);
} catch (err) { } catch (err) {
ctx.logger.error(err, 'error requiring rule module'); ctx.logger.error(err, 'error requiring rule module');
} }