I want to inject Repository in Controller.
Here is my FiedSettings Repository I have tried to follow typedi docs.
Field Setting Repository
import { Service, Container } from 'typedi';
import { Entity, PrimaryGeneratedColumn, Column, Repository } from 'typeorm';
@Service()
@Entity()
class FieldSettings {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({default : false })
is_selected: boolean;
constructor(payload: Record<string, unknown>) {
Object.assign(this, payload);
}
}
Container.set('FieldSettings', FieldSettings);
export { FieldSettings };
FieldSettingsController
import {Request} from 'express';
import { getRepository } from 'typeorm';
import { IResponse } from '@interfaces';
import { success } from '@utils/common.util';
import { FieldSettings } from '@models/field-settings.model';
class FieldSettingsController {
private static instance: FieldSettingsController;
private constructor() {
}
static get(): FieldSettingsController {
if (!FieldSettingsController.instance) {
FieldSettingsController.instance = new FieldSettingsController();
}
return FieldSettingsController.instance;
}
async createFields(req: Request, res: IResponse): Promise<void> {
try {
const fields = new FieldSettings({
name : req.body.name
})
await getRepository(FieldSettings).save(fields);
res.status(200).json(success('', {}, res.statusCode));
} catch (err) {
console.log('err', err);
res.status(400).json(success('', {}, res.statusCode));
}
}
}
const fieldSettingsController = FieldSettingsController.get();
export {fieldSettingsController as FieldSettingsController}
I tried to inject the repository
@InjectRepository(FieldSettings)
fieldSetRepo: Repository<FieldSettings>;
private static instance: FieldSettingsController;
later i tried to work with it in createFields
await this.fieldSetRepo.save(fields);
which threw error "Can't read undefined properties (reading fieldSetRepo)"
Please help me resolve this.