This repository has been archived by the owner on Oct 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.js
56 lines (46 loc) · 1.71 KB
/
validate.js
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
// This file validates the GraphQL examples against schema.sdl
// This can be adapted to create a check when docs are being built.
// Importing required modules using ES module syntax
import { buildSchema, parse, validate } from "graphql";
import fs from "fs";
import path from "path";
// 1. Load the schema SDL from a file
const schemaSDL = fs.readFileSync(
path.join(
path.resolve(),
"../commercetools-api-reference/api-specs/graphql/schema.sdl",
),
"utf-8",
);
// 2. Build the schema object from SDL
const schema = buildSchema(schemaSDL);
// 3. Define the folder where your GraphQL files are located
const graphqlFolder = path.join(path.resolve(), "graphql-files/validated");
// 4. Function to load and validate all GraphQL files in a folder
function validateGraphQLFiles(folderPath) {
// Get all files in the folder
const files = fs.readdirSync(folderPath);
// Filter only .graphql files
const graphqlFiles = files.filter((file) => file.endsWith(".graphql"));
// Iterate over each .graphql file and validate
graphqlFiles.forEach((file) => {
const filePath = path.join(folderPath, file);
const query = fs.readFileSync(filePath, "utf-8");
try {
// Parse the GraphQL query
const ast = parse(query);
// Validate the query against the schema
const errors = validate(schema, ast);
if (errors.length > 0) {
console.error(`Validation errors in ${file}:`);
errors.forEach((err) => console.error(err.message));
} else {
console.log(`${file} is valid!`);
}
} catch (err) {
console.error(`Error parsing ${file}:`, err.message);
}
});
}
// 5. Validate all GraphQL files in the specified folder
validateGraphQLFiles(graphqlFolder);