1.0.1 • Published 5 years ago

type-schema v1.0.1

Weekly downloads
91
License
MIT
Repository
github
Last release
5 years ago

Type-Schema

Build Status Coverage Status npm

Define JSON Schemas using TypeScript classes

Usage

Example #1 (Simple login schema):

import { property, arrayProperty, objectOptions, getJSONSchema } from 'type-schema';

class PostBodySchema {
  @property({ required: true })
  username: string;

  @property({ required: true })
  password: string;
}

// AJV async schema
@objectOptions({ $async: true })
class PostSchema {
  @property({ required: true })
  body: PostBodySchema;
}

const postSchema = getJSONSchema(PostSchema);

Where postSchema will be the following JSON schema:

{
  "$async": true,
  "type": "object",
  "properties": {
    "body": {
      "additionalProperties": false,
      "type": "object",
      "properties": {
        "username": {
          "type": "string"
        },
        "password": {
          "type": "string"
        }
      },
      "required": [
        "username",
        "password"
      ]
    }
  },
  "required": [
    "body"
  ]
}

Example #2 (Administration of a user by id):

import { property, arrayProperty, objectOptions, getJSONSchema } from './index';

enum Permissions {
  ADMIN = 'admin',
  USER = 'user',
  SUPER_ADMIN = 'superAdmin',
}

class PutBodySchema {
  @property()
  username: string;

  @arrayProperty({ items: String, itemOptions: { enum: Permissions } })
  permissions: string[];
}

class ParamsByIdSchema {
  @property({ required: true })
  userid: string;
}

// AJV async schema
@objectOptions({ $async: true })
class PutByIdSchema {
  @property({ required: true })
  body: PutBodySchema;

  @property({ required: true })
  params: ParamsByIdSchema;
}

const putByIdSchema = getJSONSchema(PutByIdSchema);

Where postSchema will be the following JSON schema:

{
  "$async": true,
  "type": "object",
  "properties": {
    "body": {
      "type": "object",
      "properties": {
        "username": {
          "type": "string"
        },
        "permissions": {
          "type": "array",
          "items": {
            "enum": [
              "admin",
              "user",
              "superAdmin"
            ],
            "type": "string"
          }
        }
      }
    },
    "params": {
      "type": "object",
      "properties": {
        "userid": {
          "type": "string"
        }
      },
      "required": [
        "userid"
      ]
    }
  },
  "required": [
    "body",
    "params"
  ]
}