Mikeul
Mikeul

Reputation: 61

NodeJS + TypeORM repository is undefined

I'm making a controller and I want to work with repository in my controller as you can see from the snippet below.

export class PatientController {
  patientRepository: Repository<Patient>;
  constructor() {
    // Initializing repository
    this.patientRepository = AppDataSource.getRepository(Patient);
  }
  async getAll(_req: Request, res: Response, next: NextFunction) {
    try {
      const patients = await this.patientRepository.find();
      // More logic
    } catch (err: any) {
      // Error logic
    } finally {
      next();
    }
  }
}

But when I tried it on Postman, it returns

{
    "status": 404,
    "message": "Cannot read property 'patientRepository' of undefined"
}

Upvotes: 0

Views: 539

Answers (1)

rhea-so
rhea-so

Reputation: 21

How about this?

I guess you may missed using a controller instance.

import express, { Router, Request, Response, Express } from 'express';
import { Column, DataSource, Entity, PrimaryColumn, Repository } from 'typeorm';

// Create Entity
@Entity()
export class Patient {
  @PrimaryColumn()
  id: number;

  @Column({ type: 'varchar' })
  message: string;
}

// Create DataSource
const dataSource: DataSource = new DataSource({
  type: 'sqlite',
  database: ':memory:',
  synchronize: true,
  entities: [Patient], // Insert entity class
});

// Example
class PatientController {
  private patientRepository: Repository<Patient> = null;
  constructor() {
    // Initializing repository
    this.patientRepository = dataSource.getRepository(Patient);
  }

  async create(entity: Patient): Promise<Patient> {
    return this.patientRepository.save(entity);
  }

  async getAll(_req: Request, res: Response): Promise<void> {
    const patients: Patient[] = await this.patientRepository.find();
    console.log(patients); // [ Patient { id: 1, message: 'Hello, World!' } ]
    res.json(patients);
  }
}

// Usage
async function main(): Promise<void> {
  await dataSource.initialize();
  const controller: PatientController = new PatientController();

  // Test data
  const entity: Patient = new Patient();
  entity.message = 'Hello, World!';
  console.log(await controller.create(entity)); // Patient { id: 1, message: 'Hello, World!' }

  // Router
  const router: Router = Router();
  router.get('/patient', (req: Request, res: Response) => controller.getAll(req, res));

  const app: Express = express();
  app.use('/', router);
  app.listen(3000);

  // open http://localhost:3000/patient
}

main();

Upvotes: 1

Related Questions