I’m implementing the repository pattern in my Express.js application and considering whether my service classes should be designed as singletons. Here is the current setup:
This is my Base Repository
export class BaseRepository<T extends DataBaseBaseEntity>
implements IBaseRepository<T>
{
private _repo: Repository<T>;
constructor(repo: Repository<T>) {
this._repo = repo;
}
}
This is my User Repository
export class UserRepository extends BaseRepository<UserEntity> {
constructor(private readonly repo: Repository<UserEntity>) {
super(repo);
}
}
This is my user service
export class UserService {
private _userRepository: UserRepository;
constructor() {
const _repo = DBConnection.getConnection().getRepository(UserEntity);
this._userRepository = new UserRepository(_repo);
}
async create(data: any) {
return await this._userRepository.create(data);
}
}
This is my User Controller
export class UserController {
private _userService: UserService;
constructor() {
this._userService = new UserService();
}
async create() {
return await this._userService.create({ data: "any" });
}
}
This is my User Router
export const userRouter: Router = express.Router();
const userController: UserController = new UserController();
userRouter.post("/create", async (req: Request, res: Response) => {
const createdData = await userController.create();
res.send(createdData);
});
Is this good pattern?
Would making my service classes singleton provide any benefits or drawbacks in this context?
Are there other design or structural improvements you could suggest for this setup?
I’m looking for ways to optimize the design and structure of my application. Specifically, I am curious about the implications of using the Singleton pattern for service classes in a web application context like Express.js.