I know how to run a script from command line, using npm
or npx ts-node [script.ts]
just as stated here.
My question is different, now that I can run scripts, can I use services that are inside modules in my project? Let's say that I have this structure that it is normally called inside the project by other modules:
foo/foo.module.ts
import { HttpModule, Module } from '@nestjs/common';
@Module({
providers: [FooService],
imports: [HttpModule],
exports: [FooService]
})
export class FooModule { }
foo/foo.service.ts
import { HttpService, Injectable } from '@nestjs/common';
@Injectable()
export class FooService {
constructor(
private readonly httpService: HttpService,
) {}
bar() {
console.log('do stuff');
}
}
how can I call bar()
inside the file /src/script.ts
and then call npx ts-node script.ts
keeping all the imports? Thank you.
Let say you have an application module like this:
import { Module } from '@nestjs/common';
import { UsersModule } from './users/users.module';
@Module({
imports: [
UsersModule,
],
})
export class ApplicationModule {}
And an UserService used by UsersModule in this way:
import { Module } from '@nestjs/common';
@Module({
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
And you want to create a command to create a new user directly from command line.
You can create a file named console.ts
and put the following content:
import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './application.module';
import { UsersService } from './users/users.service';
async function bootstrap() {
const application = await NestFactory.createApplicationContext(
ApplicationModule,
);
const command = process.argv[2];
switch (command) {
case 'create-administrator-user':
const usersService = application.get(UsersService);
await usersService.create({
username: 'administrator',
password: 'password',
});
break;
default:
console.log('Command not found');
process.exit(1);
}
await application.close();
process.exit(0);
}
bootstrap();
And now in your package.json
you can create the following script:
"execute": "ts-node ./src/console.ts"
Now you have the ability to call a custom command in a NestJS context like in the following example:
// Using Yarn
yarn execute create-administrator-user
// Using NPM
npm run execute create-administrator-user
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With