refactor: reintroduce validateThing method

This commit is contained in:
Rainer Killinger
2019-05-07 11:32:22 +02:00
parent f90e93c1f4
commit c4a403e807
2 changed files with 39 additions and 4 deletions

View File

@@ -182,6 +182,20 @@ export function isSchemaWithDefinitions(schema: JSONSchema): schema is SchemaWit
return typeof schema.definitions !== 'undefined';
}
// tslint:disable: completed-docs
/**
* Guard method for determining if an object (a thing) has a type property with a type of string
*
* @param thing An object (thing)
*/
export function isThingWithType(thing: unknown): thing is { type: string; } {
return typeof thing === 'object' &&
thing !== null &&
'type' in thing &&
typeof (thing as { type: string; }).type === 'string';
}
// tslint:enable: completed-docs
/**
* Get path that contains a tsconfig.json
*

View File

@@ -18,7 +18,13 @@ import {PathLike} from 'fs';
import {Schema, Validator as JSONSchemaValidator, ValidatorResult} from 'jsonschema';
import * as mustache from 'mustache';
import {basename, join, resolve} from 'path';
import {ExpectableValidationErrors, globPromisified, readFilePromisified, writeFilePromisified} from './common';
import {
ExpectableValidationErrors,
globPromisified,
isThingWithType,
readFilePromisified,
writeFilePromisified,
} from './common';
/**
* StAppsCore validator
@@ -74,12 +80,28 @@ export class Validator {
}
/**
* Validates anything against a given schema name
* Validates anything against a given schema name or infers schema name from object
*
* @param instance Instance to validate
* @param schema Name of schema to validate instance against or the schema itself
*/
public validate(instance: unknown, schema: string | Schema): ValidatorResult {
public validate(instance: unknown, schema?: string | Schema): ValidatorResult {
if (typeof schema === 'undefined') {
if (isThingWithType(instance)) {
// schema name can be infered from type string
// tslint:disable-next-line: completed-docs
const schemaSuffix = (instance as { type: string; }).type.split(' ')
.map((part: string) => {
return part.substr(0, 1)
.toUpperCase() + part.substr(1);
})
.join('');
const schemaName = `SC${schemaSuffix}`;
return this.validate(instance, schemaName);
}
throw new Error('Instance.type does not exist.');
}
if (typeof schema === 'string') {
// if you want to access a schema that is contained in the validator object
if (typeof this.schemas[schema] !== 'object') {
@@ -89,7 +111,6 @@ export class Validator {
return this.validator.validate(instance, this.schemas[schema]);
}
// if you have a schema and want to validate it directly
return this.validator.validate(instance, schema);
}
}