Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions __tests__/expose.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// tslint:disable:no-submodule-imports
import { Expose } from 'class-transformer'
import { IsString } from 'class-validator'
import { validationMetadatasToSchemas } from '../src'
const { defaultMetadataStorage } = require('class-transformer/cjs/storage')

// @ts-ignore unused
class User {
@IsString()
id: string

@Expose({ name: 'domain_id' })
@IsString()
domainId: string
}

describe('Expose() decorator', () => {
it('rename Expose()-decorated properties from output schema', () => {
const schema = validationMetadatasToSchemas({
classTransformerMetadataStorage: defaultMetadataStorage,
})

expect(schema).toEqual({
User: {
properties: {
id: { type: 'string' },
domain_id: { type: 'string' },
},
type: 'object',
required: ['id', 'domain_id'],
},
})
})
})
21 changes: 21 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type { ReferenceObject, SchemaObject } from 'openapi3-ts'
import { getMetadataSchema } from './decorators'
import { defaultConverters } from './defaultConverters'
import { defaultOptions, IOptions } from './options'
import { ExposeMetadata } from 'class-transformer'

export { JSONSchema } from './decorators'

Expand Down Expand Up @@ -64,6 +65,26 @@ export function validationMetadataArrayToSchemas(
isExcluded({ ...propMeta, target }, options)
)
)
.map((propMeta) => {
/**
* Retrieves all properties that have the Expose decorator from class-transformer
* and remaps the property names to the names exposed by the Expose decorator.
*/
const exposeMetadata =
userOptions?.classTransformerMetadataStorage?.getExposedMetadatas(
propMeta.target as any
)

const ctMetaForField = exposeMetadata?.find(
(meta: ExposeMetadata) => meta.propertyName === propMeta.propertyName
)

if (ctMetaForField?.options.name) {
propMeta.propertyName = ctMetaForField.options.name
}

return propMeta
})

const properties: { [name: string]: ReferenceObject | SchemaObject } = {}

Expand Down