-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery-parser.ts
More file actions
65 lines (54 loc) · 1.85 KB
/
query-parser.ts
File metadata and controls
65 lines (54 loc) · 1.85 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
import * as fs from 'fs';
import { CLIError, handleAndLogError } from '@contentstack/cli-utilities';
import { QueryExportConfig } from '../types';
export class QueryParser {
private config: QueryExportConfig;
constructor(config: QueryExportConfig) {
this.config = config;
}
async parse(queryInput: string): Promise<any> {
let query: any;
// Check if it's a file path
if (queryInput.endsWith('.json') && fs.existsSync(queryInput)) {
query = this.parseFromFile(queryInput);
} else {
query = this.parseFromString(queryInput);
}
this.validate(query);
return query;
}
private parseFromFile(filePath: string): any {
try {
const content = fs.readFileSync(filePath, 'utf-8');
return JSON.parse(content);
} catch (error) {
handleAndLogError(error, this.config.context, 'Failed to parse the query file');
}
}
private parseFromString(queryString: string): any {
try {
return JSON.parse(queryString);
} catch (error) {
handleAndLogError(error, this.config.context, 'Invalid JSON query');
}
}
private validate(query: any): void {
if (!query || typeof query !== 'object') {
throw new CLIError('The query must be a valid JSON object.');
}
if (!query.modules || typeof query.modules !== 'object') {
throw new CLIError('The query must contain a "modules" object.');
}
const modules = Object.keys(query.modules);
if (modules.length === 0) {
throw new CLIError('The query must contain at least one module.');
}
// Validate supported modules
const queryableModules = this.config.modules.queryable;
for (const module of modules) {
if (!queryableModules.includes(module as any)) {
throw new CLIError(`Module "${module}" is not queryable. Supported modules: ${queryableModules.join(', ')}`);
}
}
}
}