@dgcode/fields
TypeScript icon, indicating that this package has built-in type declarations

0.1.60 • Public • Published

@dgcode/fields

model-oriented fields manager for typescript

Install

$ npm install @dgcode/fields

Features

  • Browser and server-compatible
  • Properties & models crafting tool
  • Convert and map objects fields as other properties and / or transformed values
  • Displayable objects on a Google Sheet (via googleapis)
  • Save-able objects in SQL / MongoDB databases (via typeorm)

Usage

Conversion

Enables switching between two different representations of the same structure. For example, you may represent a User object in two ways; your own way (the programmatic instance), and the way provided by an external API (the resource).

// our own way
class User {
  public firstName: string
  public lastName: string
}

// the Google way (AdminDirectory API)
class UserResource {
  public name: {
    givenName: string
    familyName: string
  }
}

To create a "bridge" between those two types, you need to map firstName to name.givenName and lastName to name.familyName.

import { Field, convert } from '@dgcode/fields';

class User {

  public constructor(attrs?: Partial<User>) {
    Object.assign(this, attrs);
  }

  @Field({ path: 'name.givenName' })
  public firstName: string

  @Field({ path: 'name.familyName' })
  public lastName: string

}

Now we are free to convert a User instance to a resource:

convert(new User({ firstName: 'John', lastName: 'Doe' })).toResource();
// { name: { givenName: 'John', lastName: 'Doe' }}

And the other way around (resource-to-instance):

convert({ name: { givenName: 'Mary', familyName: 'Jane' } }).toInstance(User);
// User { firstName: 'Mary', lastName: 'Jane' }

Readme

Keywords

none

Package Sidebar

Install

npm i @dgcode/fields

Weekly Downloads

2

Version

0.1.60

License

MIT

Unpacked Size

165 kB

Total Files

57

Last publish

Collaborators

  • dgcoder