Skip to content

Commit

Permalink
Add support for additionalProperties.
Browse files Browse the repository at this point in the history
  • Loading branch information
boyko committed May 3, 2020
1 parent 9b58040 commit 82af830
Show file tree
Hide file tree
Showing 2 changed files with 102 additions and 1 deletion.
80 changes: 80 additions & 0 deletions __tests__/additionalProperties.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// 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 {
// @ts-ignore
@ValidateNested({each: true})
// @Matches(/w{10}/, {each: true})
@Type(() => {
return String
})
@MinLength(2, {each: true})
// users: User[]
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"
]
}
})
})
})
23 changes: 22 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,33 @@ function applyConverters(
options: IOptions
): SchemaObject {
const converters = { ...defaultConverters, ...options.additionalConverters }

const convert = (meta: ValidationMetadata) => {
// @ts-ignore
const typeMeta = options.classTransformerMetadataStorage
? options.classTransformerMetadataStorage.findTypeMetadata(
// @ts-ignore
meta.target,
meta.propertyName
)
: null
const isMap = typeMeta ? new typeMeta.reflectedType() instanceof Map : false;

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

const items = _.isFunction(converter) ? converter(meta, options) : converter
return meta.each ? { items, type: 'array' } : items

if (meta.each && isMap) {
// @ts-ignore
return {
additionalProperties: {
...items,
},
type: "object"
};
}
return meta.each ? {items, type: "array"} : items;
}

// @ts-ignore: array spread
Expand Down

0 comments on commit 82af830

Please sign in to comment.