primed-model
Hassle free TypeScript model management
Dynamically create your instances from JSON objects to take full advantage of OOP. This approach is to be contrasted with factory functions for managing highly structured data
Note: This project uses reflect-metadata for storing metadata in classes and properties
Model definition
Model
<decorator> - To register the classesPrimed
<decorator> - To mark properties to be dynamically instantiatedBase
<class> - To extend the models, configure their constructor's typing, and give internal functionality
Note: Cat
is being passed to the Primed
decorator as a string in the Person
class because TS/JS does not allow classes which haven't been defined to be referenced by value
Example usage
Initializing with empty constructor
Output
name: "" middleName: "" lastName: "" fullName: "Empty Name" parent: name: "" middleName: "" lastName: "" fullName: "Empty Name" cats: name: null breed: null cats: name: null breed: null
Passing JSON to constructor
name: "Alice" lastName: "Liddell" cats: name: "garfield" parent: name: "Bob" cats: name: "Tom"
Output
name: "Alice" middleName: "" lastName: "Liddell" fullName: "Alice Liddell" parent: name: "Bob" middleName: "" lastName: "" fullName: "Bob" cats: name: "Tom" breed: null cats: name: "Garfield" breed: null
Features
- Recursively and dynamically create model instances, automatically instantiated by default, unless
required: false
is specified in thePrimed
options - Specify properties for classes defined after the point of reference passing a string to
Primed
- Pass a factory function to
Primed
for custom data types - Getters are enumerable by default so that they show when iterating over the keys or in the string representation of your class (using
JSON.stringify
) - Provided
clone
method for copying whole instances
Custom properties examples
You can define your own functions that can be passed into the Prime
decorator for custom behavior
Luxon's DateTime
Decimal from decimal.js
JavaScript's Date
string id
Noteworthy
-
If you're minifying/compressing/uglyfing your JS, you must pass a string to the
Model
decorator with the name of the class. The function name is being relied uppon for initializing properties that depend on it at runtime -
Pass
required: false
to thePrimed
options to prevent primed properties from being automatically instantiated -
Pass
array: true
to thePrimed
options to automatically instantiate arrays -
If the payload type differs from the class's type and you want those typings, you can pass an second interface (which can be a partial of the class) to the
Base
class when extending -
Auto initialization will stop after detecting a circular reference
new Alpha#### Output
bravo:charlie:alpha:bravo: undefined
To do
- Add tests
- Implement change detection mechanism