@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' }