Problem z brakiem pola properties w wygenerowanym schemacie może wynikać z kilku przyczyn. Oto rozwiązania:
1. Sprawdź strukturę wygenerowanego schematu
typescript-json-schema może generować schemat w różnych formatach. Czasem główny obiekt jest w definitions, a nie bezpośrednio w schemacie:
typescript
// generate-schema-with-defaults.ts
import { createGenerator } from "ts-json-schema-generator";
import * as fs from "fs";
import * as path from "path";
try {
const configPath = path.join(__dirname, "module-config.json");
const exampleData = JSON.parse(fs.readFileSync(configPath, "utf-8"));
// Funkcja do debugowania struktury schematu
function debugSchema(schema: any, depth = 0) {
const indent = " ".repeat(depth);
console.log(indent + "Schema structure:");
console.log(indent + "- type:", schema.type);
console.log(indent + "- properties:", !!schema.properties);
console.log(indent + "- definitions:", !!schema.definitions);
console.log(indent + "- $ref:", schema.$ref);
if (schema.definitions) {
Object.keys(schema.definitions).forEach(key => {
console.log(indent + `- definition[${key}]:`, schema.definitions[key].type);
});
}
}
// Funkcja rekurencyjnie dodająca wartości domyślne
function addDefaults(schema: any, example: any): any {
// Jeśli schemat używa $ref, znajdź definicję
if (schema.$ref && schema.definitions) {
const refName = schema.$ref.replace("#/definitions/", "");
if (schema.definitions[refName]) {
schema.definitions[refName] = addDefaults(schema.definitions[refName], example);
}
return schema;
}
// Standardowe przetwarzanie dla obiektów z properties
if (schema.type === "object" && schema.properties) {
Object.keys(schema.properties).forEach((key) => {
if (example.hasOwnProperty(key)) {
schema.properties[key].default = example[key];
if (typeof example[key] === "object" &&
!Array.isArray(example[key]) &&
example[key] !== null) {
addDefaults(schema.properties[key], example[key]);
}
}
});
}
return schema;
}
// Generuj schemat
const generator = createGenerator({
path: "src/types.ts",
type: "MyType",
tsconfig: "tsconfig.json",
// Dodatkowe opcje, które mogą pomóc
expose: "export",
topRef: true,
jsDoc: "extended",
});
const schema = generator.createSchema("MyType");
// Debug: wyświetl strukturę schematu
debugSchema(schema);
// Opcja 1: Jeśli schemat używa $ref do definitions
let processedSchema = schema;
// Opcja 2: Jeśli chcesz "spłaszczyć" schemat (bez $ref)
if (schema.$ref && schema.definitions) {
const refName = schema.$ref.replace("#/definitions/", "");
if (schema.definitions[refName]) {
processedSchema = {
...schema.definitions[refName],
definitions: schema.definitions
};
}
}
// Dodaj wartości domyślne
const schemaWithDefaults = addDefaults(processedSchema, exampleData);
// Zapisz schemat
fs.writeFileSync(
"schema-with-defaults.json",
JSON.stringify(schemaWithDefaults, null, 2)
);
console.log("\nSchemat wygenerowany pomyślnie!");
} catch (error) {
console.error("Błąd podczas generowania schematu:", error);
}
2. Alternatywne podejście - bezpośrednie użycie schematu
Jeśli nadal masz problemy, możesz użyć opcji topRef: false:
typescript
const generator = createGenerator({
path: "src/types.ts",
type: "MyType",
tsconfig: "tsconfig.json",
topRef: false, // To spowoduje wygenerowanie schematu bez $ref
jsDoc: "extended",
});
3. Przykład typu TypeScript i oczekiwanego wyniku
Upewnij się, że Twój typ TypeScript jest poprawnie zdefiniowany:
typescript
// src/types.ts
export interface MyType {
name: string;
age: number;
isActive: boolean;
tags: string[];
address?: {
street: string;
city: string;
};
}
4. Funkcja pomocnicza do "rozpakowania" schematu
typescript
function resolveSchema(schema: any): any {
// Jeśli schemat ma $ref, znajdź i zwróć odpowiednią definicję
if (schema.$ref && schema.definitions) {
const refName = schema.$ref.replace("#/definitions/", "");
const definition = schema.definitions[refName];
if (definition) {
return {
...definition,
definitions: schema.definitions
};
}
}
return schema;
}
// Użycie:
const rawSchema = generator.createSchema("MyType");
const resolvedSchema = resolveSchema(rawSchema);
const schemaWithDefaults = addDefaults(resolvedSchema, exampleData);
5. Diagnostyka problemu
Dodaj ten kod, aby zobaczyć dokładnie, co generuje biblioteka:
typescript
const rawSchema = generator.createSchema("MyType");
console.log("Raw schema:", JSON.stringify(rawSchema, null, 2));
Jeśli nadal masz problemy, pokaż mi:
- Twój typ TypeScript
- Wygenerowany schemat (bez modyfikacji)
- Strukturę pliku
module-config.json
To pomoże mi dokładniej zdiagnozować problem i zaproponować lepsze rozwiązanie.