Skip to content

Commit 58b6907

Browse files
author
Sascha Goldhofer
committed
Refactor functions to TS
1 parent 98a6ea9 commit 58b6907

37 files changed

+342
-272
lines changed

lib/addValidator.js renamed to lib/addValidator.ts

+20-14
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,30 @@
1+
import Core from "./cores/CoreInterface";
2+
import { JSONValidator } from "./types";
3+
4+
15
/**
26
* @throws Error
37
* Adds a custom error. May override existing errors
48
*
5-
* @param {Core} core
6-
* @param {String} errorId - id of error @see /lib/validation/errors
7-
* @param {Function} errorCreator - function returning an error-object @see /lib/utils/createCustomError
9+
* @param core
10+
* @param errorId - id of error @see /lib/validation/errors
11+
* @param {Function} errorCreator - function returning an error-object @see /lib/utils/createCustomError
812
*/
9-
function addError(core, errorId, errorCreator) {
13+
function addError(core: Core, errorId: string, errorCreator) {
1014
if (typeof errorCreator !== "function") {
1115
throw new Error(`Error callback 'errorCreator' must be of type function. Received ${typeof errorCreator}`);
1216
}
1317
core.errors[errorId] = errorCreator;
1418
}
1519

20+
1621
/**
1722
* Adds a custom format validator. Existing format may not be overriden (may still be modified manually)
18-
* @param {Core} core
19-
* @param {String} formatType - format type (i.e. `format: "html"`)
20-
* @param {Function} validationFunction - called with (core, schema, value, pointer)
23+
* @param core
24+
* @param formatType - format type (i.e. `format: "html"`)
25+
* @param validationFunction - called with (core, schema, value, pointer)
2126
*/
22-
function addFormat(core, formatType, validationFunction) {
27+
function addFormat(core: Core, formatType: string, validationFunction: JSONValidator) {
2328
if (typeof validationFunction !== "function") {
2429
throw new Error(`Validation function expected. Received ${typeof validationFunction}`);
2530
}
@@ -30,15 +35,16 @@ function addFormat(core, formatType, validationFunction) {
3035
throw new Error(`A format '${formatType}' is already registered to validation`);
3136
}
3237

38+
3339
/**
3440
* Adds a custom keyword validation to a specific type. May not override existing keywords.
3541
*
36-
* @param {Core} core
37-
* @param {String} datatype - valid datatype like "object", "array", "string", etc
38-
* @param {String} keyword - The keyword to add, i.e. `minWidth: ...`
39-
* @param {Function} validationFunction - called with (core, schema, value, pointer)
42+
* @param core
43+
* @param datatype - valid datatype like "object", "array", "string", etc
44+
* @param keyword - The keyword to add, i.e. `minWidth: ...`
45+
* @param validationFunction - called with (core, schema, value, pointer)
4046
*/
41-
function addKeyword(core, datatype, keyword, validationFunction) {
47+
function addKeyword(core: Core, datatype: string, keyword: string, validationFunction: JSONValidator) {
4248
if (typeof validationFunction !== "function") {
4349
throw new Error(`Validation function expected. Received ${typeof validationFunction}`);
4450
}
@@ -52,7 +58,7 @@ function addKeyword(core, datatype, keyword, validationFunction) {
5258
}
5359

5460

55-
module.exports = {
61+
export default {
5662
error: addError,
5763
format: addFormat,
5864
keyword: addKeyword

lib/compile/getRef.js renamed to lib/compile/getRef.ts

+8-7
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
1-
const { get } = require("gson-pointer");
2-
const splitRef = require("./splitRef");
1+
import { get } from "gson-pointer";
2+
import splitRef from "./splitRef";
3+
import getTypeOf from "../getTypeOf";
4+
import { JSONSchema } from "../types";
5+
6+
37
const suffixes = /(#|\/)+$/g;
4-
const getTypeOf = require("../getTypeOf");
58
// const emptyValues = ["", null, "#"];
6-
79
const isObject = val => (getTypeOf(val) === "object");
810

911

1012
// 1. combined is known
1113
// 2. base or pointer is known
1214
// 3. base + pointer is known
13-
14-
module.exports = function getRef(context, rootSchema, $ref) {
15+
export default function getRef(context, rootSchema: JSONSchema, $ref) {
1516
if (isObject($ref)) {
1617
$ref = $ref.__ref || $ref.$ref;
1718
}
@@ -81,4 +82,4 @@ module.exports = function getRef(context, rootSchema, $ref) {
8182
return getRef(context, rootSchema, schema.$ref);
8283
}
8384
return schema;
84-
};
85+
}

lib/compile/index.js renamed to lib/compile/index.ts

+6-8
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
/* eslint max-statements-per-line: ["error", { "max": 2 }] */
2-
const eachSchema = require("../eachSchema");
3-
const remotes = require("../../remotes");
4-
const joinScope = require("./joinScope");
5-
const getRef = require("./getRef");
2+
import eachSchema from "../eachSchema";
3+
import remotes from "../../remotes";
4+
import joinScope from "./joinScope";
5+
import getRef from "./getRef";
6+
import { JSONSchema } from "../types";
67

78
const COMPILED = "__compiled";
89
const COMPILED_REF = "__ref";
@@ -11,7 +12,7 @@ const GET_ROOT = "getRoot";
1112
const suffixes = /(#|\/)+$/g;
1213

1314

14-
function compile(rootSchema, force = false) {
15+
export default function compile(rootSchema: JSONSchema, force = false): JSONSchema {
1516
if (rootSchema[COMPILED] !== undefined) { return rootSchema; } // eslint-disable-line
1617
const context = { ids: {}, remotes: Object.assign({}, remotes) };
1718
const rootSchemaAsString = JSON.stringify(rootSchema);
@@ -53,6 +54,3 @@ function compile(rootSchema, force = false) {
5354
// console.log(JSON.stringify(context.ids, null, 2));
5455
return rootSchema;
5556
}
56-
57-
58-
module.exports = compile;

lib/compile/joinScope.js renamed to lib/compile/joinScope.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ const isDomain = /^[^:]+:\/\/[^/]+\//;
55
const trailingFragments = /\/[^/]*$/;
66
const idAndPointer = /#.*$/;
77

8-
module.exports = function joinScope(previous, id) {
8+
export default function joinScope(previous, id) {
99
if (previous == null && id == null) { return "#"; }
1010
if (id == null) { return previous.replace(trailingHash, ""); }
1111
if (previous == null) { return id.replace(trailingHash, ""); }

lib/compile/splitRef.js renamed to lib/compile/splitRef.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ const suffixes = /(#|\/)+$/g;
22
const emptyValues = ["", null, "#"];
33

44

5-
module.exports = function splitRef($ref) {
5+
export default function splitRef($ref) {
66
if (emptyValues.includes($ref)) {
77
return [];
88
}

lib/compileSchema.js

-1
This file was deleted.

lib/compileSchema.ts

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
import compile from "./compile";
2+
export default compile;

lib/cores/CoreInterface.ts

+9-4
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,17 @@ import resolveRef from "../resolveRef.withOverwrite";
33
import compileSchema from "../compileSchema";
44
import resolveAnyOf from "../resolveAnyOf";
55
import resolveAllOf from "../resolveAllOf";
6-
import { JSONSchema, JSONPointer } from "../types";
6+
import { JSONSchema, JSONPointer, JSONError } from "../types";
77

88

99
/* eslint no-unused-vars: 0 no-empty-function: 0 */
1010
export default class CoreInterface {
1111
__rootSchema: JSONSchema;
12+
errors;
13+
typeKeywords;
14+
validateFormat;
15+
validateKeyword;
16+
validateType;
1217

1318
constructor(schema?: JSONSchema) {
1419
this.setSchema(schema);
@@ -29,11 +34,11 @@ export default class CoreInterface {
2934
throw new Error("function 'each' is not implemented");
3035
}
3136

32-
validate(data: any, schema: JSONSchema = this.rootSchema, pointer: JSONPointer = "#") {
37+
validate(data: any, schema: JSONSchema = this.rootSchema, pointer: JSONPointer = "#"): Array<JSONError> {
3338
throw new Error("function 'validate' is not implemented");
3439
}
3540

36-
isValid(data: any, schema: JSONSchema = this.rootSchema, pointer: JSONPointer = "#") {
41+
isValid(data: any, schema: JSONSchema = this.rootSchema, pointer: JSONPointer = "#"): boolean {
3742
throw new Error("function 'isValid' is not implemented");
3843
}
3944

@@ -65,7 +70,7 @@ export default class CoreInterface {
6570
this.rootSchema = schema;
6671
}
6772

68-
step(key: string, schema: JSONSchema, data: any, pointer: JSONPointer = "#") {
73+
step(key: string, schema: JSONSchema, data: any, pointer: JSONPointer = "#"): JSONSchema {
6974
throw new Error("function 'step' is not implemented");
7075
}
7176
}

lib/cores/Draft04.ts

+1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { JSONSchema, JSONPointer } from "../types";
1111

1212
import remotes from "../../remotes";
1313
import draft04 from "../../remotes/draft04.json";
14+
// @ts-ignore
1415
remotes["http://json-schema.org/draft-04/schema"] = compileSchema(draft04);
1516

1617
import TYPE_KEYWORD_MAPPING from "../validation/typeKeywordMapping";

lib/createSchemaOf.js renamed to lib/createSchemaOf.ts

+6-9
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
1-
const getTypeOf = require("./getTypeOf");
1+
import getTypeOf from "./getTypeOf";
2+
import { JSONSchema } from "./types";
23

34

45
/**
56
* Create a simple json schema for the given input data
6-
* @param {Mixed} data - data to get json schema for
7-
* @return {Object} schema
7+
* @param data - data to get json schema for
8+
* @return schema
89
*/
9-
function createSchemaOf(data) {
10-
const schema = {
10+
export default function createSchemaOf(data: any): JSONSchema {
11+
const schema: JSONSchema = {
1112
type: getTypeOf(data)
1213
};
1314

@@ -25,7 +26,3 @@ function createSchemaOf(data) {
2526

2627
return schema;
2728
}
28-
29-
30-
module.exports = createSchemaOf;
31-

lib/each.js renamed to lib/each.ts

+9-10
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
1-
const getTypeOf = require("./getTypeOf");
1+
import Core from "./cores/CoreInterface";
2+
import getTypeOf from "./getTypeOf";
3+
import { JSONSchema, JSONPointer } from "./types";
24

35

46
/**
57
* Iterates over data, retrieving its schema
68
*
7-
* @param {CoreInterface} core - validator
8-
* @param {Mixed} data - the data to iterate
9-
* @param {Function} callback - will be called with (schema, data, pointer) on each item
10-
* @param {Object} [schema] - the schema matching the data. Defaults to rootSchema
11-
* @param {String} [pointer] - pointer to current data. Default to rootPointer
9+
* @param core - validator
10+
* @param data - the data to iterate
11+
* @param callback - will be called with (schema, data, pointer) on each item
12+
* @param [schema] - the schema matching the data. Defaults to rootSchema
13+
* @param [pointer] - pointer to current data. Default to rootPointer
1214
*/
13-
function each(core, data, callback, schema = core.rootSchema, pointer = "#") {
15+
export default function each(core: Core, data: any, callback, schema: JSONSchema = core.rootSchema, pointer: JSONPointer = "#") {
1416
callback(schema, data, pointer);
1517
const dataType = getTypeOf(data);
1618

@@ -27,6 +29,3 @@ function each(core, data, callback, schema = core.rootSchema, pointer = "#") {
2729
});
2830
}
2931
}
30-
31-
32-
module.exports = each;

lib/getSchema.js

-39
This file was deleted.

lib/getSchema.ts

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import gp from "gson-pointer";
2+
import { JSONSchema, JSONPointer } from "./types";
3+
import Core from "./cores/CoreInterface";
4+
5+
6+
const emptyObject = {};
7+
8+
9+
/**
10+
* Returns the json-schema of a data-json-pointer.
11+
*
12+
* Notes
13+
* - Uses core.step to walk through data and schema
14+
*
15+
* @param core
16+
* @param pointer - json pointer in data to get the json schema for
17+
* @param [data] - the data object, which includes the json pointers value. This is optional, as
18+
* long as no oneOf, anyOf, etc statement is part of the pointers schema
19+
* @param [schema] - the json schema to iterate. Defaults to core.rootSchema
20+
* @return json schema object of the json-pointer or an error
21+
*/
22+
export default function getSchema(core: Core, pointer: JSONPointer, data?: any, schema: JSONSchema = core.rootSchema): JSONSchema {
23+
const frags = gp.split(pointer);
24+
return _get(core, schema, frags, pointer, data);
25+
}
26+
27+
28+
function _get(core: Core, schema: JSONSchema, frags: Array<string>, pointer: JSONPointer, data: any = emptyObject): JSONSchema {
29+
if (frags.length === 0) {
30+
return schema;
31+
}
32+
33+
const key = frags.shift(); // step key
34+
schema = core.step(key, schema, data, pointer); // step schema
35+
if (schema && schema.type === "error") {
36+
return schema;
37+
}
38+
data = data[key]; // step data
39+
return _get(core, schema, frags, `${pointer}/${key}`, data);
40+
}
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const toString = Object.prototype.toString;
22

3-
module.exports = function getTypeOf(value) {
3+
4+
export default function getTypeOf(value: any) {
45
// eslint-disable-next-line newline-per-chained-call
56
return toString.call(value).match(/\s([^\]]+)\]/).pop().toLowerCase();
6-
};
7+
}

lib/isValid.js

-12
This file was deleted.

lib/isValid.ts

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { JSONSchema, JSONPointer } from "./types";
2+
import Core from "./cores/CoreInterface";
3+
4+
5+
/**
6+
* Test if the data is valid according to the given schema
7+
*
8+
* @param core - validator
9+
* @param value - value to validate
10+
* @param [schema] - json schema
11+
* @param [pointer] - json pointer pointing to value
12+
* @return if schema does match given value
13+
*/
14+
export default function isValid(core: Core, value: any, schema: JSONSchema = core.rootSchema, pointer: JSONPointer = "#"): boolean {
15+
return core.validate(value, schema, pointer).length === 0;
16+
}

0 commit comments

Comments
 (0)