#Is there any ways to call service inside **main.ts**?

12 messages · Page 1 of 1 (latest)

undone wyvern
patent vapor
# undone wyvern You can get it from your app using `app.get(MyService)`. An example is in the do...

Didn't work for me maybe because I'be provided poor information. Maybe you can help me to solve this. I'm using Winston Logger for logging. So let's start from main.ts: ```
const start = async () => {
try {
const PORT = process.env.PORT || 5000;
const app = NestFactory.create(AppModule, { cors: true });
(await app).listen(PORT, () => {
console.log(server started on port ${PORT});
});
} catch (error) {
console.log(error);
}
};

start();

#

Then I created a separate module for Winston Logger like this ```
@Module({})
export class WinstonLoggerModule {
static forRoot(): DynamicModule {
return {
imports: [
WinstonModule.forRoot({
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.ms(),
nestWinstonModuleUtilities.format.nestLike('MyApp', {
colors: true,
prettyPrint: true,
}),
),
}),
new winston.transports.File({
filename: 'errors.log',
level: 'error',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.ms(),
nestWinstonModuleUtilities.format.nestLike('MyApp', {
colors: true,
prettyPrint: true,
}),
),
}),
],
// other options
}),
],
module: WinstonLoggerModule,
providers: [
{ provide: WINSTON_LOGGER_SERVICE, useClass: WinstonLoggerService },
],
exports: [WinstonLoggerModule],
};
}
}

#

And the service based on Winston logger Provider ```
@Injectable()
export class WinstonLoggerService implements IWinstonLoggerService {
constructor(
@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
) {}

warn(message): void {
this.logger.warn(message);
}

error(message): void {
this.logger.error(message);
}

debug(message): void {
this.logger.debug(message);
}

info(message): void {
this.logger.info(message);
}
}

#

For now I can inject this module to the app.module and service to the other services to log some information. But I would like to log more certain information for example context like when the services start, or as I've already noted - to log any errors when starting app from main.ts

undone wyvern
#
const start = async () => {
  try {
    const PORT = process.env.PORT || 5000;
    const app = NestFactory.create(AppModule, { cors: true });
    (await app).listen(PORT, () => {
      // This should log correctly, if you import WinstonLoggerModule.forRoot in your AppModule
      app.get(WINSTON_LOGGER_SERVICE, {strict: false}).log(`server started on port ${PORT}`);
    });
  } catch (error) {
    // App failed to create, so we can't get logger from it
    console.error(error);
  }
};

start();

There's not much you can do about the failed app create. You have to handle that without Nest. It's a chicken/egg problem.

When services start — Inject the logger in service's constructor and call logger.debug('Service started') — that's the obvious Dependency Injection way. You'll have to be more specific if that's not what you're looking for.

If something doesn't work, provide some error message, or other details about how exactly it didn't work.

patent vapor
# undone wyvern ```ts const start = async () => { try { const PORT = process.env.PORT || 5...

Oh, yes I see now that there is no way to catch such kind of errors by internal services, because the app was not created so the services as well. Sorry for disturbing, but what about the providers inside the App? For example we have custom Provider for mongoose type DataBaseProvider = { provide: string; useFactory: () => Promise<typeof mongoose>; }[]; export const databaseProviders: DataBaseProvider = [ { provide: DATABASE_CONNECTION, useFactory: async (): Promise<typeof mongoose> => await mongoose.connect(process.env.DATA_BASE_URI), }, ]; an we import it just to DataBase Module ```
@Module({
providers: [...databaseProviders],
exports: [...databaseProviders],
})
export class DBModule {}

patent vapor
hollow mantle
patent vapor
# hollow mantle NestFactory should be awaited

but it is const app = NestFactory.create(AppModule, { cors: true }); (await app).listen(PORT, () => { app .get(WINSTON_LOGGER_SERVICE, { strict: false }) .log(`server started on port ${PORT}`); }); } catch (error) { console.error(error); }

hollow mantle
#

No, it's not. app is a reference to NestFactory.create. it should be a reference to await NestFactory.create. Notice how you have to await app before calling listen? That's because it's a reference to a promise. Now, it should be fine inside of that callback, but the typings aren't great for knowing if a variable has been awaited or not so typescript is telling you it might still be a promise

patent vapor