Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"homepage": "https://github.com/sinclairzx81/typebox-codegen#readme",
"devDependencies": {
"@sinclair/hammer": "^0.17.2",
"@types/inquirer": "^9.0.7",
"@types/node": "^18.15.11",
"@types/prettier": "^2.7.2"
},
Expand Down
44 changes: 39 additions & 5 deletions src/model/model-to-json-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ import * as Types from '@sinclair/typebox'
// ModelToJsonSchema
// --------------------------------------------------------------------------
export namespace ModelToJsonSchema {
interface JsonSchemaOptions {
format?: 'js' | 'json'
}

function Any(schema: Types.TAny): Types.TSchema {
return schema
}
Expand Down Expand Up @@ -155,13 +159,43 @@ export namespace ModelToJsonSchema {
if (Types.TypeGuard.IsVoid(schema)) return Void(schema)
return UnsupportedType(schema)
}
export function Generate(model: TypeBoxModel): string {
const buffer: string[] = []

interface Formatter {
push(type: Types.TSchema, schema: Types.TSchema): void
finalize(): string
}
class JsFormatter implements Formatter {
buffer: string[] = []

push(type: Types.TSchema, schema: Types.TSchema) {
const encode = JSON.stringify(schema, null, 2)
this.buffer.push(`export const ${type.$id} = ${encode}`)
}
finalize() {
return Formatter.Format(this.buffer.join('\n'))
}
}

class JsonFormatter implements Formatter {
objs: Record<string, any> = {}

push(type: Types.TSchema, schema: Types.TSchema) {
if (type.$id !== undefined) this.objs[type.$id] = schema
}
finalize(): string {
return JSON.stringify(this.objs, null, 2)
}
}

export function Generate(model: TypeBoxModel, options?: JsonSchemaOptions): string {
const format = options?.format ?? 'js'
const formatter = format === 'js' ? new JsFormatter() : new JsonFormatter()

for (const type of model.types.filter((type) => Types.TypeGuard.IsSchema(type))) {
const schema = Visit(type)
const encode = JSON.stringify(schema, null, 2)
buffer.push(`export const ${type.$id} = ${encode}`)
formatter.push(type, schema)
}
return Formatter.Format(buffer.join('\n'))

return formatter.finalize()
}
}
Loading