class-schema is a library intended to extract from javascript class, the corrispondent JSON Schema, usually, the schema is written by hand or throught some tool that create the schema. but, with this library you can extract the schema directly from the class you defined, so you have a single source of truth of the schema SSOT that is your class.
npm install class-schemato use class-schema you also need the package reflect-metadata
npm install reflect-metadataIn order to use decorators in javascript, a transpiler that can
npm i -D babel-cliYou need to enable experimentalDecorators and emitDecoratorMetadata in your tsconfig.json
// file: tsconfig.json
{
compilerOptions: {
experimentalDecorators: true,
emitDecoratorMetadata: true,
},
}in your index you have to import reflect-metadata
import 'reflect-metadata'and you are ready to go!
import 'reflect-metadata'
import { use, schema, prop, ref, enums } from 'class-schema'
const vowels = ['a', 'e', 'i', 'o', 'u', 'y']
type Vowels = typeof vowels[number]
@schema()
class MyObject {
@enums(vowels)
myEnum: Vowels
}
@schema()
class MySchema {
@prop()
myProp: number
@array()
@prop(Number)
myPropArray: number[]
@ref(MyObject)
myObject: MyObject
}to get javascript object that represent jsonschema of class
use(MySchema)
// output of `JSON.stringify(use(MySchema))
{
type: 'object',
properties: {
myProp: {
type: 'number',
},
myPropArray: {
type: 'array',
items: {
type: 'number',
},
},
myObject: {
type: 'object',
properties: {
myEnum: {
type: 'array',
items: {
type: 'string',
enum: ['a', 'e', 'i', 'o', 'u', 'y'],
},
},
},
required: ['myEnum'],
},
},
required: ['myProp', 'myPropArray', 'myObject'],
}