0.1.3 • Published 6 months ago

@gallofeliz/typescript-transform-to-json-schema v0.1.3

Weekly downloads
-
License
ISC
Repository
-
Last release
6 months ago

typescript-transform-to-json-schema

npm.io

Note: This module is part of @gallofeliz/js-libs that is a personal project. It is not developed nor tested for applications that need high security or scalability.

Convert typescript type to jsonSchema during typescript compilation, using https://www.npmjs.com/package/ts-json-schema-generator (supporting jsDoc for example to precise regex, min, max, etc)

Configure

  • Use ttypescript (because typescript does not support custom transformers)
  • Configure tsconfig.json
{
  "compilerOptions": {
    "plugins": [
      { "transform": "@gallofeliz/typescript-transform-to-json-schema" }
    ]
  }
}

Run

ttsc or ts-node -C ttypescript index.ts

What

Resolve typescript type to JSON Schema :

import { tsToJsSchema } from '@gallofeliz/typescript-transform-to-json-schema';

interface User {
    /** @pattern /a-zA-Z+/ */
    name: string
    /** @asType integer @minimum 1 */
    id: number
}

const schema = tsToJsSchema<MyObject>();

console.log(schema);

/*
Output :
{
  '$id': 'User',
  '$schema': 'http://json-schema.org/draft-07/schema#',
  type: 'object',
  properties: {
    name: { type: 'string', pattern: '/a-zA-Z+/' },
    id: { type: 'integer', minimum: 1 }
  },
  required: [ 'name', 'id' ],
  additionalProperties: false
}
*/

Will be resolved during typescript compilation to :

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const schema = JSON.parse("{\"$id\":\"User\",\"$schema\":\"http://json-schema.org/draft-07/schema#\",\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\",\"pattern\":\"/a-zA-Z+/\"},\"id\":{\"type\":\"integer\",\"minimum\":1}},\"required\":[\"name\",\"id\"],\"additionalProperties\":false,\"definitions\":{}}");
console.log(schema);

Then, we can have :

import { tsToJsSchema } from '@gallofeliz/typescript-transform-to-json-schema';

type LightStatus = 'on' | 'off'

const myApiRoute = {
    method: 'POST',
    uri: '/light/status',
    inputBodySchema: tsToJsSchema<LightStatus>(),
    handle<LightStatus, void>(req, res): void {
        light.turn(req.body) // req.body is either on or off
    }
}

Dev

index.d.ts and index.js are commited because needed for js-libs with ts-node to avoid memory loop problems.

0.1.3

6 months ago

0.1.2

1 year ago

0.1.1

1 year ago