4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

class-transformerって結局何?

Posted at

class-transformerとは

JavaScriptには、「プレーンオブジェクト」「クラスオブジェクト」の2種類があります。

// プレーンオブジェクト
{
    "id": 1,
    "firstName": "Johny",
    "lastName": "Cage",
    "age": 27
}

// クラスオブジェクト
export class User {
  id: number;
  firstName: string;
  lastName: string;
  age: number;

  getName() {
    return this.firstName + ' ' + this.lastName;
  }
}

あるプレーンオブジェクトからあるクラスオブジェクトに変換したい時、めんどくさいやり方しかできず、実用上不都合が起きやすいです。

そのため、簡単に変換を行なってくれるライブラリがclass-transformerです。
プレーンオブジェクト↔︎クラスオブジェクトの変換が可能。

インストール方法

// yarnの場合
yarn install class-transformer

// npmの場合
npm install class-transformer

使用例

シンプルバージョン

import { plainToClass, classToPlain, Expose } from 'class-transformer';

class User {
  @Expose()
  firstName: string;

  @Expose()
  lastName: string;

  @Expose()
  age: number;
}

// プレーンなオブジェクトをクラスインスタンスに変換
const plainUser = {
  firstName: 'John',
  lastName: 'Doe',
  age: 25,
};
const user = plainToClass(User, plainUser);

// クラスインスタンスをプレーンなオブジェクトに変換
classToPlain(user);

ネスト構造バージョン

import { Type } from 'class-transformer';
import { IsString, IsInt, ValidateNested } from 'class-validator';
import { plainToClass, classToPlain } from 'class-transformer';

class Address {
  @IsString()
  street: string;

  @IsString()
  city: string;

  @IsString()
  country: string;
}

class User {
  @IsString()
  firstName: string;

  @IsString()
  lastName: string;

  @IsInt()
  age: number;

  @ValidateNested()
  @Type(() => Address)
  address: Address;
}

const plainUser = {
  firstName: 'John',
  lastName: 'Doe',
  age: 25,
  address: {
    street: '123 Main St',
    city: 'New York',
    country: 'USA'
  }
};

// プレーンなオブジェクトをクラスインスタンスに変換
const user = plainToClass(User, plainUser);

// クラスインスタンスをプレーンなオブジェクトに変換
const plain = classToPlain(user);

参考

class-transformer
class-transformerでpureなjsオブジェクトとクラスとの変換が便利だった
Class Transformerの概要について備忘録を書いた

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?