Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
class-validator-jsonschema
Advanced tools
Convert class-validator-decorated classes into OpenAPI-compatible JSON Schema. The aim is to provide a best-effort conversion: since some of the class-validator
decorators lack a direct JSON Schema counterpart, the conversion is bound to be somewhat opinionated. To account for this multiple extension points are available.
yarn add class-validator-jsonschema
import { getFromContainer, IsOptional, IsString, MaxLength, MetadataStorage } from 'class-validator'
import { validationMetadatasToSchemas } from 'class-validator-jsonschema'
class BlogPost {
@IsString() id: string
@IsOptional()
@MaxLength(20, { each: true })
tags: string[]
}
const metadatas = getFromContainer(MetadataStorage).validationMetadata
const schemas = validationMetadatasToSchemas(metadatas)
console.log(schemas)
which prints out:
{
"BlogPost": {
"properties": {
"id": {
"type": "string"
},
"tags": {
"items": {
"maxLength": 20,
"type": "string"
},
"type": "array"
}
},
"required": [
"id"
],
"type": "object"
}
}
validationMetadatasToSchemas
takes an options
object as an optional second parameter. Check available configuration objects and defaults at options.ts
.
With options.additionalConverters
you can add new validation metadata converters or override the existing ones. Let's say we want to, for example, add a handy description
field to each @IsString()
-decorated property:
import { ValidationTypes } from 'class-validator'
// ...
const schemas = validationMetadatasToSchemas(metadatas, {
additionalConverters: {
[ValidationTypes.IS_STRING]: {
description: 'A string value',
type: 'string'
}
}
})
which now outputs:
{
"BlogPost": {
"properties": {
"id": {
"description": "A string value",
"type": "string"
},
// ...
}
}
}
An additional converter can also be supplied in form of a function that receives the validation metadata item and global options, outputting a JSON Schema property object (see below for usage):
type SchemaConverter = (meta: ValidationMetadata, options: IOptions) => SchemaObject | void
class-validator
allows you to define custom validation classes. You might for example validate that a string's length is between given two values:
import { Validate, ValidationArguments, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator'
// Implementing the validator:
@ValidatorConstraint()
export class CustomTextLength implements ValidatorConstraintInterface {
validate(text: string, validationArguments: ValidationArguments) {
const [min, max] = validationArguments.constraints
return text.length >= min && text.length <= max
}
}
// ...and putting it to use:
class Post {
@Validate(CustomTextLength, [0, 11])
title: string
}
Now to handle your custom validator's JSON Schema conversion include a customValidation
converter in options.additionalConverters
:
const schemas = validationMetadatasToSchemas(
validationMetadatas,
{
additionalConverters: {
[ValidationTypes.CUSTOM_VALIDATION]: meta => {
if (meta.constraintCls === CustomTextLength) {
return {
maxLength: meta.constraints[1],
minLength: meta.constraints[0],
type: 'string'
}
}
}
}
}
)
Validation classes can also be supplemented with the JSONSchema
decorator. JSONSchema
can be applied both to classes and individual properties; any given keywords are then merged into the JSON Schema derived from class-validator decorators:
import { JSONSchema } from 'class-validator-jsonschema'
@JSONSchema({
description: 'A User object',
example: { id: '123' }
})
class BlogPost {
@IsString()
@JSONSchema({
description: 'User primary key',
format: 'custom-id'
})
id: string
}
Results in the following schema:
{
"BlogPost": {
"description": "A User object",
"example": { "id": "123" },
"properties": {
"id": {
"description": "User primary key",
"format": "custom-id",
"type": "string"
}
},
"required": ["id"],
"type": "object"
}
}
Alternatively JSONSchema
can take a function of type (existingSchema: SchemaObject, options: IOptions) => SchemaObject
. The return value of this function is then not automatically merged into existing schema (i.e. the one derived from class-validator
decorators). Instead you can handle merging yourself in whichever way is preferred, the idea being that removal of existing keywords and other more complex overwrite scenarios can be implemented here.
There's no handling for class-validator
s validation groups or conditional decorator (@ValidateIf
) out-of-the-box. The above-mentioned extension methods can be used to fill the gaps if necessary.
The OpenAPI spec doesn't currently support the new JSON Schema draft-06 keywords const
and contains
. This means that constant value decorators such as @IsEqual()
and @ArrayContains()
translate to quite complicated schemas. Hopefully in a not too distant future these keywords are adopted into the spec and we'll be able to provide neater conversion.
Handling null values is also tricky since OpenAPI doesn't support JSON Schema's type: null
, providing its own nullable
keyword instead. The default @IsEmpty()
converter for example opts for nullable
but you can use type: null
instead via options.additionalConverters
:
// ...
additionalConverters: {
[ValidationTypes.IS_EMPTY]: {
anyOf: [
{type: 'string', enum: ['']},
{type: 'null'}
]
}
}
skipMissingProperties
and @isDefined()
A Base64-encoded string
)[1.1.0] - 2017-11-30
@JSONSchema
decoratorFAQs
Convert class-validator-decorated classes into JSON schema
The npm package class-validator-jsonschema receives a total of 27,415 weekly downloads. As such, class-validator-jsonschema popularity was classified as popular.
We found that class-validator-jsonschema demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.