@muperro/tojson
TypeScript icon, indicating that this package has built-in type declarations

0.1.4 • Public • Published

ToJson

@ToJson : property decorator for Typescript.

NPM version build publish codecov


Getting Started

Prerequisites

  • Node 10+
  • Typescript 1.5+

Installation

npm install @muperro/tojson
# or
yarn add @muperro/tojson

Sample

import { ToJson, JsonValueFormat, fromObject, toJSON } from "@muperro/tojson";

class UserInfoEntity {
  @ToJson({ name: "one" })
  info1: number;

  @ToJson({ name: "two" })
  info2: string;

  @ToJson({ name: "secret", format: JsonValueFormat.BYTE_LENGTH })
  secret: string;
}

class UserEntity {
  @ToJson() // default
  id: number;
  
  @ToJson({ name: "Name" }) // rename key
  name: string;

  // custom value format
  @ToJson({ custom: (v: any) => v.substring(0, 2).padEnd(v.length, "*") })
  phone: string;

  // exclude of toJSON
  password: string;

  // date format (YYYY-MM-DD)
  @ToJson({ format: JsonValueFormat.DT_YMD })
  createdAt: Date;

  // date format (YYYY-MM-DD HH:mm:ss)
  @ToJson({ format: JsonValueFormat.DT_YMD_HMS })
  updatedAt: Date;

  // format by toJSON
  @ToJson({ format: JsonValueFormat.JSON })
  info: UserInfoEntity;
}

const info = { info1: 1, info2: "2", secret: "SECRET" }; // object
const userInfoEntity = fromObject(UserInfoEntity, info); // object to instance

const user = {
  id: 1,
  name: "user",
  phone: "1234567890",
  password: "0987654321",
  createdAt: new Date(),
  updatedAt: new Date(),
  info: userInfoEntity,
}; // objet
const userEntity = fromObject(UserEntity, user); // object to instance

const json = toJSON(userEntity);
console.log(json);
// {
//   id: 1,
//   Name: 'user',
//   phone: '12********',
//   createdAt: '2020-08-17',
//   updatedAt: '2020-08-17 22:37:42',
//   info: { one: 1, two: '2', secret: 6 }
// }

Support & Contributions

License

ToJson is licensed under a MIT License.

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 0.1.4
    0
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 0.1.4
    0
  • 0.1.3
    0
  • 0.1.2
    0

Package Sidebar

Install

npm i @muperro/tojson

Weekly Downloads

0

Version

0.1.4

License

MIT

Unpacked Size

25.5 kB

Total Files

20

Last publish

Collaborators

  • muperro