Search code examples
typeormnestclass-transformer

Typeorm using class-transformer to change value in table


I'm using Nest.js with Typeorm and library class-transformer:

import { Transform } from 'class-transformer';

@PrimaryGeneratedColumn()
@Transform(
    ({ value }) => `${value}/${moment().format('MM-YYYY')}`,
)
invoiceNumber: string;

I'm trying to generate somethink like this: 1/01-2022. But still I have only an number e.g 1 (without date).

How I can add date to incremented value?


Solution

  • You can use the transformer option.

    Specifies a value transformer (or array of value transformers) that is to be used to (un)marshal this column when reading or writing to the database. In case of an array, the value transformers will be applied in the natural order from entityValue to databaseValue, and in reverse order from databaseValue to entityValue.

    Source: TypeORM Documentation

    transformer has two methods:

    1. to: Used to marshal data when writing to the database.
    2. from: Used to unmarshal data when reading from the database.
    class YourClass {
      @Column({
        primary: true, // Marks column as primary
        transformer: {
          to(value) {
            // Transform 'invoiceNumber'
            return `${value}/${moment().format('MM-YYYY')}`;
          }
          from(value) {
            // Do nothing
            return value;
          }
        },
        /* Other options... */
      })
      invoiceNumber: string;
    }
    

    Note that the decorator is no more @PrimaryGeneratedColumn but a "simple" @Column with primary option set to true. The previous decorator is only used as a table-generated primary column. Column it creates is primary and its value is auto-generated.