1
0
Fork 0

feat(visitor): move jsonpath pick to context for modules to use

This commit is contained in:
ssube 2019-11-02 10:13:29 -05:00 committed by Sean Sube
parent 29e9462ca9
commit b99431b368
3 changed files with 41 additions and 22 deletions

View File

@ -1,5 +1,4 @@
import { ValidateFunction } from 'ajv';
import { JSONPath } from 'jsonpath-plus';
import { cloneDeep, defaultTo, isNil } from 'lodash';
import { LogLevel } from 'noicejs';
@ -39,17 +38,13 @@ export class SchemaRule implements RuleData, Visitor<RuleResult> {
}
public async pick(ctx: VisitorContext, root: any): Promise<Array<any>> {
const scopes = JSONPath({
json: root,
path: this.select,
});
const items = ctx.pick(this.select, root);
if (hasItems(scopes)) {
return scopes;
if (items.length === 0) {
ctx.logger.debug('no data selected');
}
ctx.logger.debug('no data selected');
return [];
return items;
}
public async visit(ctx: VisitorContext, node: any): Promise<RuleResult> {

View File

@ -1,5 +1,9 @@
import { isNil } from 'lodash';
export function doesExist<T>(val: T | null | undefined): val is T {
return !isNil(val);
}
export function hasItems<T>(val: Array<T> | null | undefined): val is Array<T> {
return (Array.isArray(val) && val.length > 0);
}

View File

@ -1,6 +1,8 @@
import Ajv from 'ajv';
import { JSONPath } from 'jsonpath-plus';
import { Logger, logWithLevel } from 'noicejs';
import { doesExist, hasItems } from '../utils';
import { VisitorError } from './VisitorError';
import { VisitorResult } from './VisitorResult';
@ -45,6 +47,22 @@ export class VisitorContext implements VisitorContextOptions, VisitorResult {
this.innerOptions = options.innerOptions;
}
public addSchema(name: string, schema: any): void {
this.logger.debug({
name,
schema,
}, 'adding ajv schema');
this.ajv.addSchema({
$id: name,
definitions: schema,
});
}
public compile(schema: any): Ajv.ValidateFunction {
return this.ajv.compile(schema);
}
public error(...errors: Array<VisitorError>) {
for (const err of errors) {
logWithLevel(this.logger, err.level, err.data, err.msg);
@ -59,19 +77,21 @@ export class VisitorContext implements VisitorContextOptions, VisitorResult {
return this;
}
public compile(schema: any): Ajv.ValidateFunction {
return this.ajv.compile(schema);
}
public addSchema(name: string, schema: any): void {
this.logger.debug({
name,
schema,
}, 'adding ajv schema');
this.ajv.addSchema({
$id: name,
definitions: schema,
public pick(path: string, root: any): Array<any> {
const items = JSONPath({
json: root,
path,
});
this.logger.debug({
items,
path,
}, 'path query picked items');
if (hasItems(items)) {
return items.filter(doesExist);
} else {
return [];
}
}
}