feat: validate generated schemas

Fixes #1
This commit is contained in:
Karl-Philipp Wulfert
2018-12-19 14:58:06 +01:00
parent 308235c6b4
commit 7b7299d9c4
3 changed files with 60 additions and 1 deletions

View File

@@ -12,6 +12,7 @@
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import * as ajv from 'ajv';
import {Schema as JSONSchema} from 'jsonschema';
import {join} from 'path';
import {DEFAULT_CONFIG, SchemaGenerator} from 'ts-json-schema-generator';
@@ -29,6 +30,7 @@ import {isSchemaWithDefinitions} from './common';
*/
export class Converter {
private generator: SchemaGenerator;
private schemaValidator: ajv.Ajv;
/**
* Create a new converter
@@ -56,6 +58,10 @@ export class Converter {
createParser(program, config),
createFormatter(config),
);
// create ajv instance
this.schemaValidator = new ajv();
this.schemaValidator.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
}
/**
@@ -73,8 +79,21 @@ export class Converter {
schema.id = 'https://core.stapps.tu-berlin.de/v' + version + '/lib/schema/' + type + '.json';
if (isSchemaWithDefinitions(schema)) {
const selfReference = {
...{},
...schema,
};
delete selfReference.$schema;
delete selfReference.definitions;
delete selfReference.id;
// add self reference to definitions
schema.definitions['SC' + type] = Object.assign({}, schema.properties);
schema.definitions['SC' + type] = Object.assign({}, selfReference as any);
}
if (!this.schemaValidator.validateSchema(schema)) {
throw new Error(`Generated schema for ${type} is invalid!`);
}
return schema;