fix(server): non-nullable IsOptional (#3939)

* custom `IsOptional`

* added link to source

* formatting

* Update server/src/domain/domain.util.ts

Co-authored-by: Jason Rasmussen <jrasm91@gmail.com>

* nullable birth date endpoint

* made `nullable` a property

* formatting

* removed unused dto

* updated decorator arg

* fixed album e2e tests

* add null tests for auth e2e

* add null test for person e2e

* fixed tests

* added null test for user e2e

* removed unusued import

* log key in test name

* chore: add note about mobile not being able to use the endpoint

---------

Co-authored-by: Jason Rasmussen <jrasm91@gmail.com>
This commit is contained in:
Mert
2023-09-01 12:40:00 -04:00
committed by GitHub
parent ca35e5557b
commit 9539a361e4
43 changed files with 271 additions and 243 deletions

View File

@@ -1,6 +1,6 @@
import { applyDecorators } from '@nestjs/common';
import { ApiProperty } from '@nestjs/swagger';
import { IsArray, IsNotEmpty, IsOptional, IsString, IsUUID } from 'class-validator';
import { IsArray, IsNotEmpty, IsOptional, IsString, IsUUID, ValidationOptions, ValidateIf } from 'class-validator';
import { basename, extname } from 'node:path';
import sanitize from 'sanitize-filename';
@@ -13,7 +13,7 @@ export function ValidateUUID({ optional, each }: Options = { optional: false, ea
return applyDecorators(
IsUUID('4', { each }),
ApiProperty({ format: 'uuid' }),
optional ? IsOptional() : IsNotEmpty(),
optional ? Optional() : IsNotEmpty(),
each ? IsArray() : IsString(),
);
}
@@ -92,3 +92,23 @@ export async function* usePagination<T>(
yield result.items;
}
}
export interface OptionalOptions extends ValidationOptions {
nullable?: boolean;
}
/**
* Checks if value is missing and if so, ignores all validators.
*
* @param validationOptions {@link OptionalOptions}
*
* @see IsOptional exported from `class-validator.
*/
// https://stackoverflow.com/a/71353929
export function Optional({ nullable, ...validationOptions }: OptionalOptions = {}) {
if (nullable === true) {
return IsOptional(validationOptions);
}
return ValidateIf((obj: any, v: any) => v !== undefined, validationOptions);
}