question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Feature] @IsOptionaIf()

See original GitHub issue

It would be nice if we could have conditional decorator for required/non-required properties.

Example use case:

I want to insert or update a record. When inserting a new row the title is required, but when updating the releaseYear on existing row the title column is not required.

I could get around this by creating two different classes InsertRecordParameters and UpdateRecordParamaeters but it would be nice to have eveything in one class when insert and update do not differ in terms of the parameters used.

class SaveRecordParameters {
@IsOptional() 
@IsPositive()
 id?: number;
 
@IsOptionaIf( self => !!self.id )
@MaxLength(5)
@MinLength(50)
 title?: string;

@IsOptional()
@IsNumber()
 releaseYear?: number;
}

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:4
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
NickKelly1commented, Aug 26, 2020

You can achieve this by creating your own decorator that wraps @ValidateIf.

/**
 * Mark the property as optional if the function returns truthy
 * 
 * @param optionalIfPropertyIsSet
 */
function IsOptionalIf(allowOptional: (obj: any, value: any) => boolean, options?: ValidationOptions) {
  // If required, do validate. Otherwise if null|undefined, don't validate
  return ValidateIf((obj, value) => !allowOptional(obj, value) || value != null), options)
}

class SaveRecordParameters {
  @IsOptional() 
  @IsPositive()
  id?: number;

  @IsOptionalIf(self => !!self.id)
  @MaxLength(5)
  @MinLength(50)
  title?: string;

  @IsOptional()
  @IsNumber()
  releaseYear?: number;
}
0reactions
yitzchak-ben-ezra-ecoplantcommented, Feb 23, 2021

Can someone make this PR merged?? this will be so helpful!!

Read more comments on GitHub >

github_iconTop Results From Across the Web

2021年04月_weixin_39829166的博客_CSDN博客
[Feature Request] Add support for UltiGCode. 2021-01-12. [Feature] @IsOptionaIf(). 2021-01-12 ... Feature Request: Automate the "I made one" on Thingiverse.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found