generic-factory
v1.0.13
Published
A TypeScript implementation of an abstract factory. Uses dlv for data retrieval.
Downloads
54
Maintainers
Keywords
Readme
Generic Factory
An abstract factory implementation using TypeScript. Use a single factory to create instances of any class, given raw source data, and a schema.
Basic Usage
Important - before getting started know that for this pattern to work, it's important to commit to the factory being responsible for property intilialization. In other words, any class requested from the factory should have no required constructor params (otherwise you'll receive a type error).
- Import exposed classes and schema data structure where needed like this:
import { Factory, schema } from 'generic-factory';
- Define the schema pairing a class with fields from a raw dataset. The generic Factory will iterate through your schema to populate a new class instance with all properties you define. Here is an example where I define a schema for a User class:
import { schema } from 'generic-factory';
export const userSchema: schema = [
{
property: 'Username',
keypath: 'node.name'
},
{
property: 'Email',
keypath: 'node.mail'
}
];
- Use the generic factory. Use factory to instantiate a class by passing a class type, raw data, and a schema.
const user = factory.Create(User, UserData.node, userSchema);
Use the new instance the factory created.
console.log(user.Username);
- For more details on this example, reference the
test-domain
andtests
directory for this package in node_modules.
Using a Post Processor
Post processors allow for dynamic changes to be made to raw data before the data is saved to the instance created by the factory. Three post processors are included in this repo (StringToDateProcessor
, ValueToBooleanProcessor
, & StringToIntProcessor
).
StringToDateProcessor
example
In the appropriate schema, declare the StringToDateProcessor
as shown below:
export const userSchema: schema = [
{
property: 'CreatedOn',
keypath: 'node.created'
postProcessor: new StringToDateProcessor() // <- like this
}
]
Using a custom Post Processor
You can declare any class that implements the IProcessable
interface to the postProcessor member of a schema. You can develop your own processor, similar the StringToDateProcessor
shown below:
import { IProcessable } from 'generic-factory';
export class StringToDateProcessor implements IProcessable {
public process(data: any): Date {
let stringData: string = data;
if (stringData.length === 10) {
stringData += '000'; // add milisecond precision
}
return new Date(parseInt(stringData));
}
}
You can then use your processor as your would the StringToDateProcessor
.
Development Instructions
- Pull repo and run
npm install
- Run tests by running
npm run test
- Build using
npm run build