Skip to content

Commit 107100b

Browse files
committed
Implement schema validation
1 parent 6d42f80 commit 107100b

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

tsdoc-config/src/TSDocConfigFile.ts

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,53 @@
1+
import * as fs from 'fs';
2+
import * as path from 'path';
3+
import * as Ajv from 'ajv';
4+
15
interface ITSDocConfigFileData {
26
filePath: string;
37
}
48

9+
const ajv: Ajv.Ajv = new Ajv({ verbose: true });
10+
11+
function initializeSchemaValidator(): Ajv.ValidateFunction {
12+
const jsonSchemaContent: string = fs.readFileSync(path.join(__dirname, 'schemas/tsdoc-config.schema.json'))
13+
.toString();
14+
const jsonSchema: object = JSON.parse(jsonSchemaContent);
15+
16+
return ajv.compile(jsonSchema);
17+
}
18+
19+
// Warning: AJV has a fairly strange API. Each time this function is called, the function object's
20+
// properties get overwritten with the results of the latest validation. Thus we need to be careful
21+
// to read the properties before a subsequent call may occur.
22+
const tsdocSchemaValidator: Ajv.ValidateFunction = initializeSchemaValidator();
23+
24+
interface IConfigJson {
25+
}
26+
527
export class TSDocConfigFile {
28+
629
public readonly filePath: string;
730

831
private constructor(data: ITSDocConfigFileData) {
932
this.filePath = data.filePath;
1033
}
1134

12-
public static load(filePath: string): TSDocConfigFile {
35+
public static load(jsonFilePath: string): TSDocConfigFile {
36+
const fullJsonFilePath: string = path.resolve(jsonFilePath);
37+
38+
const configJsonContent: string = fs.readFileSync(fullJsonFilePath).toString();
39+
40+
const configJson: IConfigJson = JSON.parse(configJsonContent);
41+
const success: boolean = tsdocSchemaValidator(configJson) as boolean;
42+
43+
if (!success) {
44+
const description: string = ajv.errorsText(tsdocSchemaValidator.errors);
45+
throw new Error('Error parsing config file: ' + description
46+
+ '\nError in file: ' + jsonFilePath);
47+
}
48+
1349
return new TSDocConfigFile({
14-
filePath
50+
filePath: fullJsonFilePath
1551
});
1652
}
1753
}

0 commit comments

Comments
 (0)