Tuesday 23 May 2017

Typescript/NodeJS - Circular Dependency while working with factories

I am quite new to Typescript and NodeJS, I am trying to use a factory to create objects on runtime.

As an example, the following object has property type Text, now getting that in runtime, I would like to create an instance of TextContainer:

{
type: "Text", 
name: "Title"
}

My factory looks like this:

import {BaseContainer} from "../Containers/BaseContainer";
import {TextContainer} from "../Containers/TextContainer";
/**
 * Used to dynamically create objects with different container classes
 * in runtime
 */
export static class ContainerFactory {

    // Object containing all class names and types
    private dictionary: Object;

    /**
     * Initializes factory dictionary
     */
    constructor() {
        // Initialize dictionary with classes
        this.dictionary = {
            "default": BaseContainer,
            "Text": TextContainer,
            "TextContainer": TextContainer
        }
    }

    /**
     * Builds object depending on className
     * @param className
     * @param params
     */
    build(className: string, params: Object) {
        // Return new class of type className, if not found
        // return object with class of set default class
        return className in this.dictionary ? new this.dictionary[className](params) : new this.dictionary['default'];

    }
}

The problem comes in when in BaseContainer class (which is extended by TextContainer and will be extended by many more classes that will be present in this factory) I use the factory in a function, and here comes the circular dependency, because in BaseContainer I import ContainerFactory and in ContainerFactory BaseContainer is imported.

I need the factory in BaseContainer because I have a tree-like hierarchy and the containers have children, which are containers themselves.

I'd appreciate suggestions on how to work around this issue, or how to refractor my code in order for it to work reliably. I searched for similar issues but didn't find a workaround yet.

I receive the following error in the TextContainer class (extends BaseContainer):

extendStatics(d, b);
        ^

TypeError: Object prototype may only be an Object or null: undefined



via Stefan

No comments:

Post a Comment