-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathvalidate-open-rpc-document.ts
More file actions
79 lines (75 loc) · 2.19 KB
/
validate-open-rpc-document.ts
File metadata and controls
79 lines (75 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { OpenrpcDocument as OpenRPC } from "./types";
import Ajv, { ErrorObject } from "ajv";
import JsonSchemaMetaSchema from "@json-schema-tools/meta-schema";
import applyExtensionSpec from "./apply-extension-spec";
import getExtendedMetaSchema from "./get-extended-metaschema";
/**
* @ignore
*/
/**
* Provides an error interface for OpenRPC Document validation
*
* @category Errors
*
*/
export class OpenRPCDocumentValidationError implements Error {
public name = "OpenRPCDocumentDereferencingError";
public message: string;
/**
* @param errors The errors received by ajv.errors.
*/
constructor(errors: ErrorObject[]) {
this.message = [
"Error validating OpenRPC Document against @open-rpc/meta-schema.",
"The errors found are as follows:",
JSON.stringify(errors, undefined, " "),
].join("\n");
}
}
/**
* Returns any JSON Schema validation errors that are found with the OpenRPC document passed in.
*
* @param document OpenRPC Document to validate.
*
* @returns Either true if everything checks out, or a well formatted error.
*
* @example
* ```typescript
*
* import { validateOpenRPCDocument } from "@open-rpc/schema-utils-js";
* const badOpenRPCDocument = {} as any;
*
* const result = validateOpenRPCDocument(badOpenRPCDocument);
* if (result !== true) {
* console.error(result);
* }
* ```
*
*/
export default function validateOpenRPCDocument(
document: OpenRPC
): OpenRPCDocumentValidationError | true {
if (!document) throw new Error("schema-utils-js: Internal Error - document is undefined");
const ajv = new Ajv();
ajv.addSchema(JsonSchemaMetaSchema, "https://meta.json-schema.tools");
let extMetaSchema = getExtendedMetaSchema(document.openrpc);
try {
extMetaSchema = applyExtensionSpec(document, extMetaSchema);
ajv.validate(extMetaSchema, document);
} catch (e) {
throw new Error(
[
"schema-utils-js: Internal Error",
"-----",
e,
"-----",
"If you see this report it: https://github.com/open-rpc/schema-utils-js/issues",
].join("\n")
);
}
if (ajv.errors) {
return new OpenRPCDocumentValidationError(ajv.errors as ErrorObject[]);
} else {
return true;
}
}