thiagobustamante / typescript-ioc

A Lightweight annotation-based dependency injection container for typescript.
MIT License
526 stars 64 forks source link

Handling connection errors #44

Closed med-qh closed 4 years ago

med-qh commented 5 years ago

Hi, Basically we are using the Hyperledger client to build our application and we are working on a rest api interfacing with the chain.

I have a class called HyperledgerChainClient which inherits BusinessNetworkConnection (a class provided by hyperledger) i need it to be instantiated and connected when my server starts, so my connection will always be the same. my class looks like this

@Singleton
export class HyperledgerChainClient extends BusinessNetworkConnection {
  constructor () {
    super(config.get('hyperledger.cardName'));
  }
}

To achieve this i tried creating a provider for my repository which looks like this

export const hyperLedgerRepositoryProvider: Provider = {
  get: async () => {
    const businessNetworkConnection: BusinessNetworkConnection = new BusinessNetworkConnection();
    try {
      const cardName: string = config.get('hyperledger.cardName');
      await businessNetworkConnection.connect(cardName);
      logger.info(`Connected to chain successfully using card name : ${cardName}`);
      return new AgentHyperledgerChainRepository(businessNetworkConnection);
    } catch (err) {
      logger.error(`Error while connecting to chain : ${err}`);
    }
  },
};

But for some reason the injection of my repository into my service always happen after the connection, so i am getting errors like

error: Error creating agent : TypeError: this.chainAgentRepository.createAgent is not a function
info: POST /agent 201 7 - 32.612 ms
error: Error while connecting to chain : Error: Failed to load connector module "composer-connector-hlfv1" for connection type "hlfv1". The gRPC binary module was not installed. This may be fixed by running "npm rebuild"

(The connection error is normal i have not yet initialized my chain). Also my only problem actually comes from the injection of my repository into my services. I already use the hyperledger package on other projects and it works fine so i am guessing the problem comes from my code ?.

Please tell me if this is unclear. Also how would you deal with injecting repositories connected to other than hyperledger such as databases per example. As i need it to be connected only once at the start.

thiagobustamante commented 4 years ago

The problem is that you are trying to make an async injection to the container and it is not supported by this library

The container has a sync interface when you try to retrieve an instance:

let instance = Container.get(SomeType);  // so I need providers that returns synchronously