Add language validation

This commit is contained in:
Nayam Amarshe
2024-12-15 14:25:18 +05:30
parent f3af1d08d8
commit c7bf9c14f8
9 changed files with 254 additions and 10 deletions

View File

@@ -0,0 +1,52 @@
function generateSchema(json) {
if (json === null) {
return { type: "null" };
}
const type = Array.isArray(json) ? "array" : typeof json;
const schema = { type };
switch (type) {
case "object":
const properties = {};
const required = [];
for (const [key, value] of Object.entries(json)) {
properties[key] = generateSchema(value);
required.push(key);
}
schema.properties = properties;
if (required.length > 0) {
schema.required = required;
}
break;
case "array":
if (json.length > 0) {
// Assume all items in array are of the same type as the first item
schema.items = generateSchema(json[0]);
}
break;
}
return schema;
}
module.exports = { generateSchema };
// Example usage:
/*
const obj = {
name: "John",
age: 30,
address: {
street: "123 Main St",
city: "Boston"
},
hobbies: ["reading", "swimming"]
};
const schema = generateSchema(obj);
console.log(JSON.stringify(schema, null, 2));
*/

View File

@@ -0,0 +1,36 @@
const Ajv = require("ajv");
const path = require("path");
const fs = require("fs");
const { generateSchema } = require("./generate-schema");
const ajv = new Ajv();
console.log("Validating language files...");
// Load the base language file (en.json)
const enJsonPath = path.join(__dirname, "..", "renderer", "locales", "en.json");
const enJson = JSON.parse(fs.readFileSync(enJsonPath, "utf-8"));
// Generate the schema for en.json
const enSchema = generateSchema(enJson);
const validate = ajv.compile(enSchema);
// Validate other language files
const localesDir = path.join(__dirname, "..", "renderer", "locales");
const languageFiles = fs
.readdirSync(localesDir)
.filter((file) => file !== "en.json");
languageFiles.forEach((file) => {
const filePath = path.join(localesDir, file);
const jsonData = JSON.parse(fs.readFileSync(filePath, "utf-8"));
const valid = validate(jsonData);
if (!valid) {
console.error(`Errors in ${file}:`);
console.error(validate.errors);
} else {
console.log(`${file} is valid.`);
}
});