Giter VIP home page Giter VIP logo

Comments (9)

Rmannn avatar Rmannn commented on May 30, 2024

The problem is that your method seedOrganization is not binded to your instance.
There are 2 simple ways to fix it.

You can bind your method in your constructor.

constructor(...){
    this.seedOrganization = this.seedOrganization.bind(this);
    // your code
}

Or you can declare your method in your class using arrow function. (see how we declare functions in the readme using the service)

seedOrganization = async (): Promise<boolean> => {
    // your code
}

from nestjs-console.

kashyap-aditya avatar kashyap-aditya commented on May 30, 2024

Thank you. I'll try that and get back to you.

from nestjs-console.

kashyap-aditya avatar kashyap-aditya commented on May 30, 2024

This worked perfectly.
I also have a documentation request:
Can you add a section showing how to accept commands such as:

console help

instead of

npm run console --help

(basically want to skip typing 'npm run' at the start)

from nestjs-console.

Rmannn avatar Rmannn commented on May 30, 2024

This is not easy cause you have dev env and production env, different shells and path structure...
In dev env, you're using typescript, ts-node.
In production you're using node.

You could add a Shebang (e.g #!/usr/bin/node) at top of your console file, see (https://docs.npmjs.com/files/package.json#bin)
Once compiled, if your module is installed as an external package you could use npx to call the binary.
Or you could invoke the binary using his path without the need to call node.
If your console is in the fodler "build/bin" you could call the console build/bin/console.js help

If you really want to call the binary directly, you could add it to your computer Env variable PATH.

Do not forget to make the binary executable using the command chmod +x path/to/the/binary.

from nestjs-console.

kashyap-aditya avatar kashyap-aditya commented on May 30, 2024

Follow up question:

I inject a repository using

@InjectRepositor(User)
private readonly userRepository: Repository<User>

When I try to access any function of this repository (such as findOne), I get an error saying - Cannot read property 'findOne' of undefined.
Here is the function in which I try to access the repository:


getAUser = async (): Promise<User> => {
    let user:User = await this.userRepository.findOne({where:{email:'[email protected]'}}
}

from nestjs-console.

Rmannn avatar Rmannn commented on May 30, 2024

Is your repository correctly intialised in your module? Is your module imported by the module you load in the console bootstrap ?
I can't help you without a git repository reproducing the error.

from nestjs-console.

kashyap-aditya avatar kashyap-aditya commented on May 30, 2024

from nestjs-console.

kashyap-aditya avatar kashyap-aditya commented on May 30, 2024

Running npm run console:dev -- getAUser fails with the error:

TypeError: Cannot read property 'findOne' of undefined

Here is cli.service.ts.

import { Injectable } from '@nestjs/common';
import { ConsoleService } from 'nestjs-console';
import { User } from '@app/model/entity/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class CliService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    private readonly consoleService: ConsoleService,
  ) {
    // get the root cli
    const cli = this.consoleService.getCli();

    // just for debugging. REMOVE BEFORE PUSHING
    this.consoleService.createCommand(
      {
        command: 'getAUser',
      },
      CliService.prototype.getAUser,
      cli,
    );
  }

  async getAUser(): Promise<User> {
    let user: User;
    try {
      user = await this.userRepository.findOne({
        where: {
          loginEmail: '[email protected]',
        },
      });
    } catch (error) {
      throw new Error('ERROR ATTEMPTING TO GET USER. ' + error);
    }
    return Promise.resolve(user);
  }
}
 

Here is my cli.module


import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LoggerModule } from 'nestjs-pino';
import { CliService } from '@app/cli/cli.service';
import { ConsoleModule } from 'nestjs-console';
import { User } from '@app/model/entity/user.entity';


@Module({
  imports: [
    TypeOrmModule.forFeature([
      User,
    ]),
    TypeOrmModule.forRoot(),
    LoggerModule.forRoot(),
    ConsoleModule,
  ],
  providers: [CliService],
  exports: [CliService],
})
export class CliModule {}

And If I create a cli.controller.ts, and run the app using npm:start, it works just fine.

import { Controller, Get } from '@nestjs/common';
import { CliService } from './cli.service';

@Controller('db')
export class CliController {
  constructor(private readonly cliService: CliService) {}

  @Get('/user')
  public async seed() {
    await this.cliService.getAUser();
  }
}


Here is the console.ts file


import { BootstrapConsole } from 'nestjs-console';
import { CliModule } from '@app/cli/cli.module';

const bootstrap = new BootstrapConsole({
  module: CliModule,
  useDecorators: false,
});
bootstrap.init().then(async app => {
  try {
    // init your app
    await app.init();
    // boot the cli
    await bootstrap.boot();
    process.exit(0);
  } catch (e) {
    process.exit(1);
  }
});

from nestjs-console.

kashyap-aditya avatar kashyap-aditya commented on May 30, 2024

Solution:


this.consoleService.createCommand(
      {
        command: 'getAUser',
      },
      CliService.prototype.getAUser.bind(this),
      cli,
    );

Added .bind(this)

from nestjs-console.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.