|
| 1 | +import * as fs from 'fs'; |
| 2 | +import * as path from 'path'; |
| 3 | +import * as Ajv from 'ajv'; |
| 4 | + |
1 | 5 | interface ITSDocConfigFileData {
|
2 | 6 | filePath: string;
|
3 | 7 | }
|
4 | 8 |
|
| 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 | + |
5 | 27 | export class TSDocConfigFile {
|
| 28 | + |
6 | 29 | public readonly filePath: string;
|
7 | 30 |
|
8 | 31 | private constructor(data: ITSDocConfigFileData) {
|
9 | 32 | this.filePath = data.filePath;
|
10 | 33 | }
|
11 | 34 |
|
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 | + |
13 | 49 | return new TSDocConfigFile({
|
14 |
| - filePath |
| 50 | + filePath: fullJsonFilePath |
15 | 51 | });
|
16 | 52 | }
|
17 | 53 | }
|
0 commit comments