forked from near/near-api-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgen_error_types.js
More file actions
87 lines (78 loc) · 2.43 KB
/
Copy pathgen_error_types.js
File metadata and controls
87 lines (78 loc) · 2.43 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
80
81
82
83
84
85
86
87
const https = require('https');
const fs = require('fs');
const {
Project,
Scope,
} = require('ts-morph');
const ERROR_SCHEMA_URL =
'https://raw.githubusercontent.com/nearprotocol/nearcore/84a805e0fe4d507d03d6525f68fec99b7d1d6048/chain/jsonrpc/res/rpc_errors_schema.json';
const TARGET_DIR = process.argv[2] || process.cwd() + '/src.ts/generated';
const TARGET_TS_FILE_PATH = TARGET_DIR + '/rpc_error_types.ts';
const TARGET_SCHEMA_FILE_PATH = TARGET_DIR + '/rpc_error_schema.json';
https
.get(ERROR_SCHEMA_URL, resp => {
let data = '';
resp.on('data', chunk => {
data += chunk;
});
resp.on('end', () => {
const jsonSchema = JSON.parse(data);
genErrorTypes(jsonSchema, TARGET_TS_FILE_PATH);
fs.writeFileSync(TARGET_SCHEMA_FILE_PATH, data);
});
})
.on('error', err => {
console.log('Unable to fetch schema file: ' + err.message);
});
function getSuperClassFor(schema, typeName) {
for (let tyName in schema) {
for (let subtype of schema[tyName].subtypes) {
if (typeName === subtype) {
return tyName;
}
}
}
return undefined;
}
function genErrorClass(schema, sourceFile, tyName) {
if (sourceFile.getClass(tyName)) {
return;
}
const superClassName = getSuperClassFor(schema, tyName);
if (superClassName) {
genErrorClass(schema, sourceFile, superClassName);
}
const classDecl = sourceFile.addClass({
name: tyName
});
if (superClassName) {
classDecl.setExtends(superClassName);
} else {
classDecl.setExtends('TypedError');
}
const type = schema[tyName];
classDecl.setIsExported(true);
for (let prop in type.props) {
classDecl.addProperty({
name: prop,
type: type.props[prop],
initializer: null,
scope: Scope.Public
});
}
}
function genErrorTypes(jsonSchema, targetFilePath) {
const project = new Project({});
const sourceFile = project.createSourceFile(targetFilePath, '', {
overwrite: true
});
sourceFile.addImportDeclaration({
moduleSpecifier: '../utils/errors'
}).addNamedImport('TypedError');
const classMap = {};
for (let tyName in jsonSchema.schema) {
classMap[tyName] = tyName;
genErrorClass(jsonSchema.schema, sourceFile, tyName);
}
sourceFile.saveSync();
}