FoalTS / foal

Full-featured Node.js framework 🚀
https://foalts.org/
MIT License
1.9k stars 142 forks source link

Is it possible to use dependecy injection from scripts? #748

Closed opensas closed 4 years ago

opensas commented 4 years ago

I'm not sure if it's possible to use dependency injection in a script, just like when you are working on your foalts app.

I tried with the following:

import { createConnection } from 'typeorm';
import { dependency, createService } from '@foal/core';
import { Hello } from '../app/services/hello.service';

export const schema = {
  additionalProperties: false,
  properties: {
    /* To complete */
  },
  required: [ /* To complete */ ],
  type: 'object',
};

class MyClass {
  @dependency
  hello: Hello

  sayHi(lang = '') {
    return this.hello.sayHi(lang)
  }
}

export async function main(args: any) {
  await createConnection();

  console.log('hi!')

  // const myClass = new MyClass()
  const myClass = createService(MyClass)

  console.log(myClass.sayHi())
}

But either using const myClass = new MyClass() or const myClass = createService(MyClass) gives the same error (in fact, the generated hello.js is identical):

$ foal run hello
hi!
(node:21180) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'sayHi' of undefined
    at MyClass.sayHi (/home/sas/devel/apps/foalts/my-app/build/scripts/hello.js:26:27)
    at main (/home/sas/devel/apps/foalts/my-app/build/scripts/hello.js:37:25)
(node:21180) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:21180) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I think it would be a nice addition to foalts being able to use dependency injection in scripts, just like how you do it form a foalts application.

LoicPoullain commented 4 years ago

The example is working on my host without any errors. Are you sure you re-ran the npm run build:scripts command (or npm run build:scripts:w for watch mode)?

opensas commented 4 years ago

:facepalm: :facepalm: :facepalm:

Ooops, everything works great. I'm sorry to waste you time

Thanks a lot