0.6.1 ā€¢ Published 2 years ago

@vodyani/transformer v0.6.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Vodyani transformer

āš— "transformer" offered simple-to-use decorators and conversion mechanisms.

Npm Npm Npm License codecov Workflow semantic-release: angular

Installation

npm install @vodyani/transformer

Features

Class transformer usage

  • Before you start using it, you need to understand some basic concepts šŸ˜„
  • The transformation capability of the class is implemented based on the class-transformer package.

Because excludeExtraneousValues is enabled by default. you needs import @Expose To mark whether the property needs to be assembled.

import { Expose } from '@vodyani/transformer'

class User {
  @Expose()
  public name: string;

  @Expose()
  public age: number;
}

Similarly, if you want to exclude certain attributes at load time, use the @Exclude decorator.

import { Expose, Exclude } from '@vodyani/transformer'

class Customer {
  @Expose()
  public name: string;

  @Exclude()
  public address: number;
}

Properties of a class will of course have nested structures, and when this happens, you need to use @Type decorator.

  • Array structures will be handled automatically just like object structures.
  • Because the @Type decorator does not properly convert nested structures in Set, you need to use @TransformSet
  • Because the @Type decorator does not properly convert nested structures in Map, you need to use @TransformMap
import { Expose, Exclude, Type } from '@vodyani/transformer'

class Book {
  @Expose()
  public name: string;
}

class LibraryOwner {
  @Expose()
  public name: string;
}

class Library {
  @Expose() @Type(() => Book)
  public books: Book[];

  @Expose() @Type(() => Book)
  public books: Book[];

  @Expose() @Type(() => LibraryOwner)
  public owner: LibraryOwner;
}

Next, check out the awesome features that @vodyani/transformer has done šŸŽ‰

FeaturesTypeDescription
toAssemblemethodThis technique turns an object into an instance of a particular class.
AssembledecoratorFollowing the function's successful completion, the result is automatically loaded using the class that was supplied.
TransformValuedecoratorThe transformation decorator of the data.
TransformSetdecoratorThe transformation decorator of the Set data.
TransformMapdecoratorThe transformation decorator of the Map data.

toAssemble

This technique turns an object into an instance of a particular class.

Params

paramtypedescription
typeClassThe intended class for conversion.
dataobjectThe source of data conversion.
optionsClassTransformOptionsThe class-transformer options. (excludeExtraneousValues is enabled by default)

Return

plainToClass result.

Example

import { Expose, toAssemble } from '@vodyani/transformer'

class User {
  @Expose()
  public name: string;

  @Expose()
  public age: number;
}

toAssemble(User, { name: 'demo' }) // { name: 'demo', age: undefined }
toAssemble(User) // { name: undefined, age: undefined }

class Customer {
  @Expose()
  public name: string;

  @Exclude()
  public address: number;
}

toAssemble(Customer, { name: 'demo' }) // { name: 'demo' }

Tips

Assemble

Following the function's successful completion, the result is automatically loaded using the class that was supplied.

Tips:

This decorator should only be used if the return value is specified šŸ¤”

Params

paramtypedescription
typeClassThe intended class for conversion.
dataobjectThe source of data conversion.
optionsClassTransformOptionsThe class-transformer options. (excludeExtraneousValues is enabled by default)

Example

import { Assemble, Expose, TransformValue, toNumber } from '@vodyani/transformer'

class Order {
  @Expose() @TransformValue((id: number) => toNumber(id, 0))
  public id: number;
}

class OrderRecord {
  @Assemble(Order)
  public get(): Promise<Order> {
    return null;
  }
}

const user = new OrderRecord().get(); // { id: 0 }

TransformValue

The transformation decorator of the data. @TransformValue actually calls the @Transform

Params

paramtypedescription
transformerMethodThe process that carries out the transition.
...argsany[]The transformer argument.

Example

import { Expose, TransformValue, toNumber } from '@vodyani/transformer'

class User {
  @Expose() @TransformValue((name: string) => toString(name, 'demo'))
  public name: string;

  @Expose() @TransformValue(toNumber)
  public age: number;
}

toAssemble(User) // { name: 'demo', age: 0 }

TransformSet

The transformation decorator of the Set data. It doesn't need to be used with @Type

Params

paramtypedescription
typeClassThe intended class for conversion.
optionsClassTransformOptionsThe class-transformer options. (excludeExtraneousValues is enabled by default)
import { Expose, TransformSet } from '@vodyani/transformer'

class Book {
  @Expose()
  public name: string;
}

class Library {
  @Expose() @TransformSet(Book)
  public books: Set<Book>;
}

TransformMap

The transformation decorator of the Map data. It doesn't need to be used with @Type

Params

paramtypedescription
typeClassThe intended class for conversion.
optionsClassTransformOptionsThe class-transformer options. (excludeExtraneousValues is enabled by default)
import { Expose, TransformMap } from '@vodyani/transformer'

class Book {
  @Expose()
  public name: string;
}

class Library {
  @Expose() @TransformMap(Book)
  public books: Map<Book>;
}

Convert transformer usage

FeaturesTypeDescription
toConvertmethodThe process that carries out the transition.
toStringmethodConvert data to string.
toNumbermethodConvert data to number.
toBuffermethodConvert Buffer data to Stream.
toStreammethodConvert Stream data to Buffer.
ResultTransformerdecoratorA transformer is passed in after the function has completed execution to change the function's output.
ArgumentTransformerdecoratorThe function's arguments are modified using the passed transformer before the function is called.

toConvert

The process that carries out the transition.

Tips:

  • There are two outcomes that return the default: default is entered and either the condition fails or the value is null.
  • This is a higher-order method that you usually need to use in conjunction with other utility functions. šŸ˜›
paramtypedescription
dataanyData that needs to be transformed.
optionsConvertOptionsOptions in transformation processing.
export interface ConvertOptions {
  /**
   * When the received value does not correspond to expectations, this value is returned.
   *
   * @default null
   */
  default?: any;
  /**
   * The conversion is carried out if the outcome of the conditional validation function execution is true.
   *
   * @empale (num: number) => num > 0
   */
  condition?: Method;
  /**
   * The process that carries out the transition.
   *
   * @empale (data: any) => Number(data)
   */
  transformer?: Method;
}

Return

T | any

Example

import { toConvert } from '@vodyani/transformer';

toConvert(undefined, { default: 1 }); // 1
toConvert(null); // null
toConvert(1, { default: 10 }); // 1
toConvert(1); // 1

How do you build a transformation function ā†“

import { toConvert } from '@vodyani/transformer';

function toString(data: any, defaultValue = ''): string {
  return toConvert(data, {
    transformer: String,
    default: defaultValue,
    condition: (data) => !isNil(data) && !isEmpty(String(data)),
  });
}

toString(undefined, '1'); // '1'
toString(null); // ''

toString

Convert data to string.

Params

paramtypedescription
dataanyData that needs to be transformed.
defaultValuestringThis value is returned when the incoming value does not match expectations.

Return

string

Example

import { toString } from '@vodyani/transformer';

toString(undefined, '1'); // '1'
toString(null); // ''
toString(1, '10'); // '1'
toString('1', '10'); // '1'

toNumber

Convert data to number.

Params

paramtypedescription
dataanyData that needs to be transformed.
defaultValuenumberThis value is returned when the incoming value does not match expectations.

Return

number

Example

import { toNumber } from '@vodyani/transformer';

toNumber(undefined, 1); // 1
toNumber(null); // 0
toNumber(1, 10); // 1
toNumber('1', 10); // 1
toNumber(Number('test'), 1); // 1

toBuffer

Convert Stream data to Buffer.

Params

paramtypedescription
streamStreamThe stream data.

Return

Promise<Buffer>

Example

import { toBuffer } from '@vodyani/transformer';

await toBuffer(data) // => stream data

toStream

Convert Buffer data to Stream.

Params

paramtypedescription
bufferBufferThe buffer data.
encodingascii/utf8/utf-8/utf16le/ucs2/ucs-2/base64/base64url/latin1/binary/hexThe encoding type.

Return

Promise<Duplex>

Example

import { toStream } from '@vodyani/transformer';

await toStream(data) // => buffer data

ResultTransformer

A transformer is passed in after the function has completed execution to change the function's output.

Params

paramtypedescription
transformerFunctionThe process that carries out the transition.

Example

import { ResultTransformer, toString, toNumber } from '@vodyani/transformer';

class Demo {
  @ResultTransformer(toString)
  public getName() {
    return null;
  }

  @ResultTransformer(toNumber)
  public async getRemoteName() {
    return null;
  }
}

const demo = new Demo();

demo.getName(); // ''
await demo.getRemoteName(); // 0

ArgumentTransformer

Params

The function's arguments are modified using the passed transformer before the function is called.

paramtypedescription
transformerFunctionThe process that carries out the transition.

Example

import { ArgumentTransformer } from '@vodyani/transformer';

function fn(...args: any[]) {
  return args.map(toNumber);
}

class Demo {
  @ArgumentTransformer(fn)
  public returnAge(age: number) {
    return age;
  }
}

const demo = new Demo();

demo.returnAge('1' as any); // 1

Team

ChoGathK
ChoGathK

License

Vodyani transformer is MIT licensed.