1.0.0 • Published 4 years ago

@brunost/ngx-model-adapter v1.0.0

Weekly downloads
1
License
MIT
Repository
gitlab
Last release
4 years ago

ngx-model-adapter

Model adapter service for Angular utilizing class-validator and class-transformer

Note: Only tested in 7.x, but should work with 6.x and later.

Installation

npm i -S ngx-model-adapter class-transformer class-validator

Example Usage

import { HttpClient } from "@angular/common/http";
import { ModelAdapter } from "ngx-model-adapter";
import { IsString, IsNumber } from "class-validator";
import { Expose, Transform } from "class-transformer";

// Define a model
export class Model {
  @IsString()
  @Expose({ name: "modelStr" })
  public str: string;

  @IsNumber()
  @Transform(v => Number.parseInt(v, 10), { toClassOnly: true })
  @Transform(v => String(v), { toPlainOnly: true })
  public num: number;
}

@Component(...)
export class AppComponent {

  constructor(
    private readonly http: HttpClient,
    private readonly modelAdapter: ModelAdapter
  ) {}
  
  // Get data from server and map to model
  public getModel() {
    this.http.get(url).pipe(
      this.modelAdapter.toModel(Model)
    ).subscribe(
      (model: Model) => console.log(model),
      (err: HttpErrorResponse|ValidationError[]) => console.error(err)
    );
  }

  // Get array of data from server and map to array of models
  public getModels() {
    this.http.get(url).pipe(
      this.modelAdapter.toModel([Model]) // note the brackets
    ).subscribe(
      (models: Model[]) => console.log(models),
      (err: HttpErrorResponse|Array<ValidationError[]>) => console.error(err)
    );
  }

  // Map model to plain object and post to server
  public postModel(model: IModel) {
    this.modelAdapter.fromModel(Model, model).pipe(
      switchMap(plain => this.http.post(url, plain))
    ).subscribe(
      () => console.log("200 OK"),
      (err: HttpErrorResponse|ValidationError[]) => console.error(err)
    );
  }

}