1 min read

Transformer

Transformer helps to convert plain objects into classes and back. Transformable classes can use pre-compiled transformers which makes this transition fast.

Installation

npm install @poq/transform

Usage example

import {
Transformable,
TProperty,
Transformer,
MapConverter
} from '@poq/transform';
// For undefined values null will be set.
@Transformable({ nullify: false })
class License {
// Defines property level default value.
@TProperty({ defaultValue: 'Default term' })
readonly terms: string;
@TProperty()
readonly signed: boolean;
@TProperty({ type: Date })
readonly verified: Date | null;
}
@Transformable()
class User {
@TProperty() readonly name: string;
@TProperty() readonly age: number;
}
@Transformable()
class OrgDocument {
@TProperty({ type: new MapConverter(User) })
readonly executives: Map<string, User>;
@TProperty({ name: 'workers', type: [User] })
readonly employees: User[];
@TProperty({ type: License })
readonly workLicense: License;
}
// Used to speed up transformer functions for registered classes.
Transformer.precompile();
const plainObj = {
workLicense: {
terms: 'some terms',
signed: true,
verified: '2021-09-04T08:45:18.910Z'
},
workers: [
{ name: 'Sam Sam', age: 24 },
{ name: 'Jack Apple', age: 19 }
],
executives: {
'John MackDuck': { name: 'John MacDuck', age: 35 },
'John Doe': { name: 'John Doe', age: 39 }
}
};
const document = Transformer.toType(plainObj, OrgDocument);
console.dir(document);
/*
result:
OrgDocument {
employees: [
User { name: 'Sam Sam', age: 24 },
User { name: 'Jack Apple', age: 19 }
],
executives: Map(2) {
'John MackDuck' => User { name: 'John MacDuck', age: 35 },
'John Doe' => User { name: 'John Doe', age: 39 }
},
workLicense: License {
terms: 'some terms',
signed: true,
verified: 2021-09-04T08:45:18.910Z
}
}
*/