Skip to content

Commit

Permalink
Merge pull request epiphone#35 from boyko/additional-properties
Browse files Browse the repository at this point in the history
Additional properties
  • Loading branch information
epiphone authored Jun 3, 2020
2 parents 5470368 + abbaf4f commit 020159c
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
76 changes: 76 additions & 0 deletions __tests__/additionalProperties.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// tslint:disable:no-submodule-imports
import { IsString, MinLength, ValidateNested } from 'class-validator'
import { validationMetadatasToSchemas } from '../src'
import { Type } from 'class-transformer'
import { defaultMetadataStorage } from 'class-transformer/storage'

class User {
@IsString()
name: string;
}

// @ts-ignore: not referenced
class Post {
@Type(() => {
return String
})
@MinLength(2, {each: true})
userStatus: Map<string, string>
}

// @ts-ignore: not referenced
class PostWidthUsers {
@ValidateNested({each: true})
@Type(() => User)
users: Map<string, User>
}

describe('classValidatorConverter', () => {
it('combines converted class-validator metadata into JSON Schemas', async () => {
const schemas = validationMetadatasToSchemas({
classTransformerMetadataStorage: defaultMetadataStorage,
})
expect(schemas).toEqual({
"User": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object",
"required": [
"name"
]
},
"Post": {
"properties": {
"userStatus": {
"additionalProperties": {
"minLength": 2,
"type": "string"
},
"type": "object"
}
},
"type": "object",
"required": [
"userStatus"
]
},
"PostWidthUsers": {
"properties": {
"users": {
"additionalProperties": {
"$ref": "#/definitions/User"
},
"type": "object"
}
},
"type": "object",
"required": [
"users"
]
}
})
})
})
16 changes: 16 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,27 @@ function applyConverters(
options: IOptions
): SchemaObject {
const converters = { ...defaultConverters, ...options.additionalConverters }

const convert = (meta: ValidationMetadata) => {
const typeMeta = options.classTransformerMetadataStorage?.findTypeMetadata(
meta.target as Function,
meta.propertyName
)
const isMap = typeMeta && new typeMeta.reflectedType() instanceof Map

const converter =
converters[meta.type] || converters[cv.ValidationTypes.CUSTOM_VALIDATION]

const items = _.isFunction(converter) ? converter(meta, options) : converter

if (meta.each && isMap) {
return {
additionalProperties: {
...items,
},
type: 'object',
}
}
return meta.each ? { items, type: 'array' } : items
}

Expand Down

0 comments on commit 020159c

Please sign in to comment.