graphql-modules icon indicating copy to clipboard operation
graphql-modules copied to clipboard

V1 `OnInit` equivilent?

Open zomble opened this issue 6 years ago • 8 comments

I'm not specifically in need of OnInit interface being implemented, but there are module level services I would like instantiated after application creation.

My first assumption was that possibly because of instantiateAll() in createApplication() it would instantiate them. I then assumed, that it may only instantiate application level services. Which seems reasonable given the implementation of createApplication, but then it is called in ModuleFactory as well. However nothing appears to instantiate from instantiateAll(). Only when something is specifically requested from .get(), but that is what instantiateAll does..

I am a little confused by instantiateAll?

It is super useful using having this behaviour to be able to inject in additional data, provide services etc from other modules into common concepts. ie, modules providing rules for logic system, but on module owned concepts.

zomble avatar Oct 12 '20 09:10 zomble

As I was writing this comment, to check my sanity I wrote

import { createApplication, createModule, Injectable, gql } from '../src';

test('instantiateAll', async () => {
  let constructorCalled = false;

  @Injectable()
  class DoSomethingStart {
    constructor() {
      console.log('Hello');
      constructorCalled = true;
    }
  }

  const mod = createModule({
    id: 'test',
    providers: [],
    typeDefs: gql`
      type Query {
        ping: String
      }
    `,
    resolvers: {},
  });

  createApplication({ modules: [mod], providers: [DoSomethingStart] });

  expect(constructorCalled).toEqual(true);
});

This passes. Though I don't see this when using createApplication() in my project. Hmm, I am using 1.0.0-alpha-9f800b1.0

zomble avatar Oct 12 '20 09:10 zomble

It was late, I've now made sure I had the latest version of the project, and instantiateAll is not in the project. The above does not pass in master.

zomble avatar Oct 12 '20 23:10 zomble

We're going to support it, not sure about the implementation and if it happen before v1.0 but definitely before v1.1.

kamilkisiela avatar Oct 26 '20 18:10 kamilkisiela

@kamilkisiela I was thinking about this after screwing around.

I did this mess as an idea:

After createApp

for (let module of modules) {
    logger.debug(`bootstrapping ${module.id}`)
    if (module.providers) {
      for (let provider of module.providers) {
        const info = normaliseDiProvider(provider)
        if (info.global && info.scope == Scope.Singleton && info.name.endsWith("Bootstrap")) {
          logger.debug(`initializing ${info.name}`)
          injector.get(info.provides)
        }
      }
    }
  }

... lol. (didn't bother rolling it up into something nice, just an idea)

I was thinking about this, and a solution in general (instead of specific OnInit implementations in the core DI). If a provider could be tagged, in anyway: eg tags: ["zomblesBootstrap"] (though this isn't strictly necessary), and some funcs could be passed into the app, and be given access to ReflectiveInjector, one could a lot of crazy things with the DI system.

Something like https://symfony.com/doc/current/service_container/compiler_passes.html but simpler, like a func chain like you've got for the middlewares?

I could easily initialise things I tagged bootstrap or equiv reflectiveInjector.tagged("zomblesBootstrap").map(Injector.get). Or in a pass collect providers, and inject them into things, like rule providers an so on etc.

Alternatively, specific implementation could have a provider marked for OnInit, onInit: true, initialise on app create.

Lots of ways to solve this, I personally would prefer something that lets me decide / add crazy stuff to my app dep resolution, over the core solving specific problems for me.

Should I reopen this?

zomble avatar Oct 26 '20 23:10 zomble

As you mentioned your intention to support it, I am reopening. Cheers!

zomble avatar Oct 30 '20 01:10 zomble

@zomble all singleton services are now instantiated when createApplication is called.

kamilkisiela avatar Nov 09 '20 14:11 kamilkisiela

Is it enough for you? We hope to have a few lifecycle hooks available in one of next minor versions.

I thought about something very simple which will give users freedom to use it however they want to, still just an idea.

createApplication({
  on: {
    bootstrap() {
      console.log('application:start');
    },
    operation({ injector, context }) {
      console.log('operation:start');
      return () => {
        console.log('operation:end');
      }
    },
    error({ }) {
    }
  }
})

kamilkisiela avatar Nov 09 '20 15:11 kamilkisiela

@kamilkisiela yup, moving to the latest alpha, and removing my crappy hack, I am seeing global singleton providers being instantiated.

Good idea. nice and simple.

zomble avatar Nov 10 '20 00:11 zomble