Recently, I developed a feature module named "user" which includes a controller, model, and services to interact with my postgres database. Despite setting up everything correctly, I encountered an error when trying to call userService from the feature module controller:
[RpcExceptionsHandler] Cannot read property 'get_users' of undefined
TypeError: Cannot read property 'get_users' of undefined
at UserController.get (/usr/src/app/dist/user/controller/user.controller.js:23:33)
at /usr/src/app/node_modules/@nestjs/microservices/context/rpc-context-creator.js:44:33
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async /usr/src/app/node_modules/@nestjs/microservices/context/rpc-proxy.js:11:32
at async ServerTCP.handleMessage (/usr/src/app/node_modules/@nestjs/microservices/server/server-tcp.js:55:54)
Below is a snippet from my user.controller.ts file:
import { Logger } from '@nestjs/common';
import { UserI } from '../models/user.interface';
import { UserService } from '../service/user.service';
import { MessagePattern } from '@nestjs/microservices';
export class UserController {
private logger = new Logger('AppController');
constructor(private readonly userService: UserService) {}
@MessagePattern('add_user')
async add(user: UserI) {
return this.userService.add(user);
}
@MessagePattern('get_user')
async get() {
return this.userService.get_users();
}
}
Extract from user.service.ts:
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { from } from 'rxjs';
import { Repository } from 'typeorm';
import { UserEntity } from '../models/user.entity';
import { UserI } from '../models/user.interface';
@Injectable()
export class UserService {
constructor(
@InjectRepository(UserEntity)
private userRepository: Repository<UserEntity>
) {}
add(user: UserI) {
return this.userRepository.save(user);
}
get_users() {
return this.userRepository.find();
}
}
Snippet from user.module.ts:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserController } from './controller/user.controller';
import { UserEntity } from './models/user.entity';
import { UserService } from './service/user.service';
@Module({
imports:[
TypeOrmModule.forFeature([UserEntity])
],
providers: [UserService],
controllers: [UserController]
})
export class UserModule {}
app.module.ts setup:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from '@nestjs/config';
import { UserModule } from './user/user.module';
@Module({
imports: [
ConfigModule.forRoot({isGlobal:true}),
TypeOrmModule.forRoot({
type: 'postgres',
url: process.env.DATABASE_URL,
autoLoadEntities: true,
synchronize: true
}),
UserModule
],
controllers: [],
providers: [],
})
export class AppModule {}