How to use tv4

Comprehensive tv4 code examples:

How to use tv4.error:

34
35
36
37
38
39
40


module.exports.Schemas = {
  get: tv4.getSchema,
  map: tv4.getSchemaMap,
  error: tv4.error
};

How to use tv4.dropSchemas:

34
35
36
37
38
39
40
41
42
43
/**
 * Drop all schemas from tv4 cache.
 * @returns {undefined}
 */
function dropSchemas() {
  tv4.dropSchemas();
  tv4.addSchema(schemaSchema);
}

/**

How to use tv4.resolveUrl:

42
43
44
45
46
47
48
49
50
51
Schemas.prototype.getSchema = function(schema, baseUri, urlHistory) {

  if (typeof schema === 'string') {
    var uri = schema;
    baseUri = baseUri || 'http://schema.ninjablocks.com/';
    var resolvedUri = tv4.resolveUrl(baseUri, uri);
    schema = tv4.getSchema(resolvedUri);
    if (!schema) {
      throw new Error('Failed to resolve schema $ref. ' + (urlHistory? Object.keys(urlHistory).join(', ') : uri));
    }

How to use tv4.addFormat:

145
146
147
148
149
150
151
152
153
154
exports.getPrettySpecs = function () {
    return specs.bundled;
};

exports.addFormat = function (format, validationFunction) {
    tv4.addFormat(format, validationFunction);
};

/**
 * Validate an arbitrary object against a model definition in a given specification

How to use tv4.reset:

47
48
49
50
51
52
53
54
55
56
 * without the explicit version.
 */
const getImplicitLegacySchemaVersion = (jsonSchema) => {
  const [schemaVersion] = [['draftV4', metaSchemaV4]].find(
    ([_, metaSchema]) => {
      tv4.reset();
      tv4.addSchema('', metaSchema);
      tv4.addSchema(metaSchema.$schema, metaSchema);
      const validationResult = tv4.validateResult(jsonSchema, metaSchema);
      return validationResult.valid;

How to use tv4.errorCodes:

294
295
296
297
298
299
300
301
302
303
````
tv4.defineKeyword('my-custom-keyword', function (data, value, schema) {
        if (simpleFailure()) {
                return "Failure";
        } else if (detailedFailure()) {
                return {code: tv4.errorCodes.MY_CUSTOM_CODE, message: {param1: 'a', param2: 'b'}};
        } else {
                return null;
        }
});

How to use tv4.getSchemaMap:

154
155
156
157
158
159
160
161
162
##### getSchemaMap()

Return a shallow copy of the schema cache, mapping schema document URIs to schema objects.

````
var map = tv4.getSchemaMap();

var schema = map[uri];
````

How to use tv4.addSchema:

48
49
50
51
52
53
54
55
56
57
 */
const getImplicitLegacySchemaVersion = (jsonSchema) => {
  const [schemaVersion] = [['draftV4', metaSchemaV4]].find(
    ([_, metaSchema]) => {
      tv4.reset();
      tv4.addSchema('', metaSchema);
      tv4.addSchema(metaSchema.$schema, metaSchema);
      const validationResult = tv4.validateResult(jsonSchema, metaSchema);
      return validationResult.valid;
    }

How to use tv4.getSchema:

146
147
148
149
150
151
152
153
154
Return a schema from the cache.

* `uri` the uri of the schema (may contain a `#` fragment)

````js
var schema = tv4.getSchema('http://example.com/schema');
````

##### getSchemaMap()

How to use tv4.freshApi:

200
201
202
203
204
205
206
207
208
##### freshApi()

Return a new tv4 instance with no shared state.

````
var otherTV4 = tv4.freshApi();
````

##### reset()

How to use tv4.validateMultiple:

96
97
98
99
100
101
102
103
104
105

this.convertAllDates(instance);
this.checkObjects = [];
this.clear(instance);
// TODO
let results = tv4.validateMultiple(instance, schema);

results['errors'].forEach((error) => {
    if (error['schemaPath'].indexOf('required') !== -1) {
        let propName = error['dataPath'] + '/' + error['params']['key'];

How to use tv4.getSchemaUris:

166
167
168
169
170
171
172
173
174
175
Return an Array with known schema document URIs.

* `filter` optional RegExp to filter URIs

````
var arr = tv4.getSchemaUris();

// optional filter using a RegExp
var arr = tv4.getSchemaUris(/^https?://example.com/);
````

How to use tv4.getMissingUris:

181
182
183
184
185
186
187
188
189
190
Use this in combination with `tv4.addSchema(uri, schema)` to preload the cache for complete synchronous validation with.

* `filter` optional RegExp to filter URIs

````
var arr = tv4.getMissingUris();

// optional filter using a RegExp
var arr = tv4.getMissingUris(/^https?://example.com/);
````

How to use tv4.validateResult:

37
38
39
40
41
42
43
44
45
46
## Usage 2: Multi-threaded validation

Storing the error and missing schemas does not work well in multi-threaded environments, so there is an alternative syntax:

```javascript
var result = tv4.validateResult(data, schema);
```

The result will look something like:
```json

How to use tv4.validate:

946
947
948
949
950
951
952
953
954
955
    const data = fs.readFileSync(file, "utf8");
    if (configRe.test(data)) {
      const config = data.replace(configRe, "$1");
      t.true(
        // @ts-ignore
        tv4.validate(JSON.parse(config), configSchemaStrict),
        file + "\n" + JSON.stringify(tv4.error, null, 2));
    }
  }
});