class-transformer icon indicating copy to clipboard operation
class-transformer copied to clipboard

feature: set default option for plainToClass and others

Open skobaken opened this issue 6 years ago • 2 comments

Description

Passing options such as excludeExtraneousValues to every plainToClass call is too tiring and leads to bug. I want to set default options.

import { setClassTransformOptions, plainToClass }

setClassTransformOptions({excludeExtraneousValues: true})
const obj = plainToClass(User, userJson) // behaves as plainToClass(User, userJson, {excludeExtraneousValues: true})

https://github.com/typestack/class-transformer/blob/develop/src/ClassTransformer.ts#L20 In other words, I want to change this empty object in some way.

Proposed solution

I have two idea to implement this.

  1. Like above, setClassTransformOptions saves default options. it is passed to ClassTransformer.
  2. create ClassTransformer field to store default options and uses it when creating ClassTransformer. Users need to create own TransformOperationExecutor to use default options.

I have no idea about behavior when both default options and options passed by method exist.

  1. default options are entirely ignored
  2. merge both options

skobaken avatar Dec 02 '20 15:12 skobaken

The advice for this scenario to wrapp class-transformer in a custom function which does do that:

import { plainToClass as originalPlainToClass } from 'class-transformer';
import { defaultOptions } from './your-custom-options.constant'

function plainToClass(obj, option) {
  return originalPlainToClass(User, userJson, { ...defaultOptions, ...options});
} 

NoNameProvided avatar Feb 14 '21 16:02 NoNameProvided

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

github-actions[bot] avatar Mar 17 '21 00:03 github-actions[bot]