ClassTransformer.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { TransformOperationExecutor } from './TransformOperationExecutor';
  2. import { TransformationType } from './enums';
  3. import { defaultOptions } from './constants/default-options.constant';
  4. export class ClassTransformer {
  5. instanceToPlain(object, options) {
  6. const executor = new TransformOperationExecutor(TransformationType.CLASS_TO_PLAIN, {
  7. ...defaultOptions,
  8. ...options,
  9. });
  10. return executor.transform(undefined, object, undefined, undefined, undefined, undefined);
  11. }
  12. classToPlainFromExist(object, plainObject, options) {
  13. const executor = new TransformOperationExecutor(TransformationType.CLASS_TO_PLAIN, {
  14. ...defaultOptions,
  15. ...options,
  16. });
  17. return executor.transform(plainObject, object, undefined, undefined, undefined, undefined);
  18. }
  19. plainToInstance(cls, plain, options) {
  20. const executor = new TransformOperationExecutor(TransformationType.PLAIN_TO_CLASS, {
  21. ...defaultOptions,
  22. ...options,
  23. });
  24. return executor.transform(undefined, plain, cls, undefined, undefined, undefined);
  25. }
  26. plainToClassFromExist(clsObject, plain, options) {
  27. const executor = new TransformOperationExecutor(TransformationType.PLAIN_TO_CLASS, {
  28. ...defaultOptions,
  29. ...options,
  30. });
  31. return executor.transform(clsObject, plain, undefined, undefined, undefined, undefined);
  32. }
  33. instanceToInstance(object, options) {
  34. const executor = new TransformOperationExecutor(TransformationType.CLASS_TO_CLASS, {
  35. ...defaultOptions,
  36. ...options,
  37. });
  38. return executor.transform(undefined, object, undefined, undefined, undefined, undefined);
  39. }
  40. classToClassFromExist(object, fromObject, options) {
  41. const executor = new TransformOperationExecutor(TransformationType.CLASS_TO_CLASS, {
  42. ...defaultOptions,
  43. ...options,
  44. });
  45. return executor.transform(fromObject, object, undefined, undefined, undefined, undefined);
  46. }
  47. serialize(object, options) {
  48. return JSON.stringify(this.instanceToPlain(object, options));
  49. }
  50. /**
  51. * Deserializes given JSON string to a object of the given class.
  52. */
  53. deserialize(cls, json, options) {
  54. const jsonObject = JSON.parse(json);
  55. return this.plainToInstance(cls, jsonObject, options);
  56. }
  57. /**
  58. * Deserializes given JSON string to an array of objects of the given class.
  59. */
  60. deserializeArray(cls, json, options) {
  61. const jsonObject = JSON.parse(json);
  62. return this.plainToInstance(cls, jsonObject, options);
  63. }
  64. }
  65. //# sourceMappingURL=ClassTransformer.js.map