-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwriteSchemas.ts
More file actions
64 lines (55 loc) · 1.75 KB
/
writeSchemas.ts
File metadata and controls
64 lines (55 loc) · 1.75 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
import fs from "node:fs"
import path from "node:path"
import {JSONSchema} from "json-schema-to-ts"
function isNotJSONSchemaArray(schema: JSONSchema | ReadonlyArray<JSONSchema>): schema is JSONSchema {
return !Array.isArray(schema)
}
function collapseExamples(schema: JSONSchema): JSONSchema {
if (typeof schema !== "object" || schema === null) {
return schema
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result: any = {...schema}
if (Array.isArray(schema.examples) && schema.examples.length > 0) {
result.example = schema.examples[0]
delete result.examples
}
if (schema.items) {
if (isNotJSONSchemaArray(schema.items)) {
result.items = collapseExamples(schema.items)
} else {
result.items = schema.items.map(collapseExamples)
}
}
if (schema.properties) {
const properties: Record<string, JSONSchema> = {}
for (const key in schema.properties) {
if (Object.hasOwn(schema.properties, key)) {
properties[key] = collapseExamples(schema.properties[key])
}
}
result.properties = properties
}
return result
}
export function writeSchemas(
schemas: Record<string, JSONSchema>,
outputDir: string
): void {
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, {recursive: true})
}
for (const name in schemas) {
if (Object.hasOwn(schemas, name)) {
const schema = schemas[name]
const fileName = `${name}.json`
const filePath = path.join(outputDir, fileName)
try {
fs.writeFileSync(filePath, JSON.stringify(collapseExamples(schema), null, 2))
console.log(`Schema ${fileName} written successfully.`)
} catch (error) {
console.error(`Error writing schema ${fileName}:`, error)
}
}
}
}