diff --git a/__tests__/expose.test.ts b/__tests__/expose.test.ts new file mode 100644 index 0000000..b07196f --- /dev/null +++ b/__tests__/expose.test.ts @@ -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'], + }, + }) + }) +}) diff --git a/src/index.ts b/src/index.ts index 6ffa99b..ff1865a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' @@ -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 } = {}