First of all awesome project, we really enjoy using the platform!
Previously we were using NestJS and enjoyed using their 'standalone application' feature: https://docs.nestjs.com/standalone-applications
This would allow us to utilize the benefits of DI without the overhead of listening for HTTP requests.
A good use case for us is when we leverage a background task system like BullMQ and want to sandbox our background tasks . Having access to the DB and other services is made easier if we can inject them or pull them out of the container.
Do you have any thoughts or suggestions on how this would be possible here?
Hello @ITninja04
Yes it's totally possible. @tsed/di is completely separated from the @tsed/common (server) package.
For example, the Ts.ED cli use @tsed/di and @tsed/core (https://github.com/TypedProject/tsed-cli/blob/master/packages/cli-core/src/Cli.ts)
You can find a small example to create your own container here:
https://www.npmjs.com/package/@tsed/di
If you need more advanced usecase tell me :)
See you
romain
This PR https://github.com/TypedProject/tsed/pull/1079 allow the creation of a small di container with mongoose database access.
The most import things is this code:
import {importProviders} from "@tsed/di";
import {getValue} from "@tsed/core";
import {createContainer, InjectorService, setLoggerLevel} from "@tsed/di";
import {$log} from "@tsed/logger";
import {MDBConnection, MongooseModule} from "@tsed/mongoose";
export interface MongooseFactoryOptions extends Omit<TsED.Configuration, "mongoose"> {
databases: Omit<MDBConnection, "id"> | MDBConnection[];
}
$log.name = "TSED";
/**
* Create injector and services for a mongoose application in standalone.
*
* @param settings
* @param container
*/
export async function mongooseFactory(settings: MongooseFactoryOptions, container = createContainer()): Promise<InjectorService> {
const injector = new InjectorService();
injector.logger = $log;
// @ts-ignore
injector.settings.set({
...settings,
logger: {
...getValue(settings, "logger", {}),
level: getValue(settings, "logger.level", "off")
},
mongoose: settings.databases
});
setLoggerLevel(this.injector);
await importProviders(this.injector);
// Clone all providers in the container
injector.addProviders(container);
// Resolve all configuration
injector.resolveConfiguration();
injector.settings.forEach((value, key) => {
injector.logger.debug(`settings.${key} =>`, value);
});
injector.invoke(MongooseModule);
await injector.load(container);
return injector;
}
@Romakita that works, thank you so much for sending this over!