Command not working with nestjs v9
See original GitHub issueIs there an existing issue for this?
- I have searched the existing issues
Current behavior
Command “crun create-admin” not working
Minimum reproduction code
CommandModule
import { Module } from '@nestjs/common';
import { TypeOrmModule } from "@nestjs/typeorm";
import { CreateAdminCommand } from './create-admin.command';
import { CreateAdminQuestions } from './questions/create-admin.questions';
import { User } from '../entities/user.entity';
@Module({
imports: [
TypeOrmModule.forRoot(),
TypeOrmModule.forFeature([
User,
]),
],
providers: [
CreateAdminCommand,
CreateAdminQuestions,
],
exports: [],
})
export class CommandModule {
}
CreateAdminCommand
import { Command, CommandRunner, Inquirer, InquirerService, Option } from 'nest-commander';
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import bcrypt from 'bcrypt';
import { userType } from '../constants/enum';
import { User } from '../entities/user.entity';
@Command({
name: 'create-admin',
description: 'Create a system admin',
arguments: '[email] [password] [userName]'
})
export class CreateAdminCommand extends CommandRunner {
constructor(
private readonly inquirer: InquirerService,
@InjectRepository(User) private userRepo: Repository<User>,
) {
super()
}
async run(
passedParam: string[],
options: { isDefault: true }
): Promise<void> {
const answers = await this.inquirer.prompt<{ email: string, password: string, userName: string}>(
'create-admin-questions',
undefined
)
const email = answers.email;
const pass = answers.password;
const userName = answers.userName;
// Password hashing
const salt = await bcrypt.genSalt();
const passwordHash = await bcrypt.hash(pass, salt);
try {
await this.userRepo.save({
email: email,
password: passwordHash,
userName: userName,
loginType: userType.ADMIN,
isActive: true,
emailVerified: true,
})
console.log('\nCreate admin successfully.');
} catch (err) {
console.log('\nFailed to create admin.');
}
}
@Option({
flags: '-s, --shell <shell>',
})
parseShell(val: string) {
return val;
}
}
CreateAdminQuestions
import { Question, QuestionSet } from "nest-commander";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import Validator from 'validatorjs';
import { User } from '../../entities/user.entity';
@QuestionSet({ name: 'create-admin-questions' })
export class CreateAdminQuestions {
constructor(
@InjectRepository(User) private userRepos: Repository<User>,
) {}
@Question({
type: 'input',
message: 'Please enter your email:',
name: 'email',
validate: async function (email: string) {
let rules = {
email: 'required|string|email',
};
let validation = new Validator({email: email}, rules);
if (validation.fails()) {
const firstErrors = validation.errors.first('email');
console.log(`\n${firstErrors}`);
return false;
}
const hasAccount = await this.loginRepos.findOne({
where:{email: email.trim()}
});
if (hasAccount) {
console.log('\nAccount already exist.');
return false;
}
return true;
}
})
parseEmail(email: string) {
return email;
}
@Question({
type: 'input',
message: 'Please enter your username:',
name: 'userName',
validate: function (userName: string) {
let rules = {
userName: 'required|string|max:64',
};
let validation = new Validator({userName: userName}, rules);
if (validation.fails()) {
const firstErrors = validation.errors.first('userName');
console.log(`\n${firstErrors}`);
return false;
}
return true;
}
})
parseFn(userName: string) {
return userName;
}
@Question({
type: 'password',
message: 'Please enter your password:',
name: 'password',
validate: function (password: string) {
Validator.register('checkPassword', function(value, requirement, attribute) {
return value.match(/((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z]).*$/);
}, 'Password too weak.');
let rules = {
password: 'required|string|min:8|max:64|checkPassword',
};
let validation = new Validator({password: password}, rules);
if (validation.fails()) {
const firstErrors = validation.errors.first('password');
console.log(`\n${firstErrors}`);
return false;
}
return true;
}
})
parsePw(password: string) {
return password;
}
}
cli.js
#!/usr/bin/env node
import { CommandFactory } from "nest-commander";
import { CommandModule } from './commands/command.module';
async function bootstrap() {
await CommandFactory.run(CommandModule);
}
bootstrap();
package.json
"bin": {
"crun": "dist/src/cli.js"
},
Then run: “crun create-admin” and nothing happen.
Expected behavior
That command runs exactly.
Package
-
nest-commander
-
nest-commander-schematics
-
nest-commander-testing
Package version
3.1.0
Node.js version
16.18.0
In which operating systems have you tested?
- macOS
- Windows
- Linux
Other
NestJs v9
Issue Analytics
- State:
- Created a year ago
- Comments:6 (3 by maintainers)
Top Results From Across the Web
When installing the V9 version, the installation fails using nest ...
I have searched the existing issues Potential Commit/PR that introduced the ... Failed to execute command: node @nestjs/schematics:resource --name=test ...
Read more >Usage - CLI | NestJS - A progressive Node.js framework
CLI command reference ; --dry-run, Reports changes that would be made, but does not change the filesystem. Alias: -d. --skip-git ; --dry-run, Reports...
Read more >nest Command not found - Stack Overflow
Working through a NestJS/Mongo DB tutorial i stumbled into this very same problem. After trying all of the solutions that were listed above, ......
Read more >NestJS v9 is now available - Trilon Consulting
In case you're not familiar with NestJS, it is a TypeScript Node.js ... Now in your terminal, start the REPL with the following...
Read more >How to use configurable module builders in NestJS v9
Increase the development speed of your NestJS application by creating your own basic, configurable module.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@jmcdo29 I found the error of import Typeorm to CommandModule, it not related to nest-commander. Sorry for that and thanks for your support.
After adding in a
Logger
to debugI can’t just run the reproduction. So please, make it so that I can.