Skip to content

Commit

Permalink
Add undefined in union support
Browse files Browse the repository at this point in the history
  • Loading branch information
vinnymac committed Apr 3, 2021
1 parent 265bce6 commit 3c414c5
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
8 changes: 8 additions & 0 deletions lib/plugin/utils/ast-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,14 @@ export function isNull(type: Type) {
}
}

export function isUndefined(type: Type) {
if (type.isUnion()) {
return Boolean(type.types.find((t) => hasFlag(t, TypeFlags.Undefined)));
} else {
return hasFlag(type, TypeFlags.Undefined);
}
}

export function hasFlag(type: Type, flag: TypeFlags) {
return (type.flags & flag) === flag;
}
Expand Down
6 changes: 3 additions & 3 deletions lib/plugin/visitors/model-class.visitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import {
getDecoratorArguments,
getMainCommentAndExamplesOfNode,
getText,
hasFlag,
isEnum,
isNull
isNull,
isUndefined
} from '../utils/ast-utils';
import {
extractTypeArgumentIfArray,
Expand Down Expand Up @@ -147,7 +147,7 @@ export class ModelClassVisitor extends AbstractFileVisitor {
): ts.ObjectLiteralExpression {
const type = typeChecker.getTypeAtLocation(node);
const isRequired = !node.questionToken;
const isNullable = !!node.questionToken || isNull(type);
const isNullable = !!node.questionToken || isNull(type) || isUndefined(type);

let properties = [
...existingProperties,
Expand Down
12 changes: 11 additions & 1 deletion test/plugin/fixtures/nullable.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@ export class NullableDto {
stringValue: string | null;
@ApiProperty()
stringArr: string[] | null;
@ApiProperty()
optionalString?: string;
@ApiProperty()
undefinedString: string | undefined;
}
`;

export const nullableDtoTextTranspiled = `export class NullableDto {
static _OPENAPI_METADATA_FACTORY() {
return { stringValue: { required: true, nullable: true, type: () => String }, stringArr: { required: true, nullable: true, type: () => [String] } };
return { stringValue: { required: true, nullable: true, type: () => String }, stringArr: { required: true, nullable: true, type: () => [String] }, optionalString: { required: false, nullable: true, type: () => String }, undefinedString: { required: true, nullable: true, type: () => String } };
}
}
__decorate([
Expand All @@ -18,4 +22,10 @@ __decorate([
__decorate([
ApiProperty()
], NullableDto.prototype, "stringArr", void 0);
__decorate([
ApiProperty()
], NullableDto.prototype, "optionalString", void 0);
__decorate([
ApiProperty()
], NullableDto.prototype, "undefinedString", void 0);
`;

0 comments on commit 3c414c5

Please sign in to comment.