Skip to content

Commit

Permalink
Merge pull request #21 from edwinhern/refactor/ModuleStructure
Browse files Browse the repository at this point in the history
refactor: Module Structure
  • Loading branch information
edwinhern authored Jan 19, 2024
2 parents 4839f6d + fea71ee commit a129fbb
Show file tree
Hide file tree
Showing 7 changed files with 51 additions and 90 deletions.
15 changes: 0 additions & 15 deletions src/modules/healthCheck/healthCheckController.ts

This file was deleted.

17 changes: 11 additions & 6 deletions src/modules/healthCheck/healthCheckRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import express, { Router } from 'express';
import express, { Request, Response, Router } from 'express';

import { HealthCheckController } from './healthCheckController';
import { ServiceResponse } from '@common/models/serviceResponse';
import { handleServiceResponse } from '@common/utils/responseHandler';

const router: Router = express.Router();
const controller: HealthCheckController = new HealthCheckController();
export const healthCheckRouter: Router = (() => {
const router = express.Router();

router.get('/', controller.status);
router.get('/', (_req: Request, res: Response) => {
const serviceResponse = new ServiceResponse(true, 'Service is healthy.', null);
handleServiceResponse(serviceResponse, res);
});

export const healthCheckRouter: Router = router;
return router;
})();
23 changes: 0 additions & 23 deletions src/modules/user/userController.ts

This file was deleted.

17 changes: 6 additions & 11 deletions src/modules/user/userRepository.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
import { User } from '@modules/user/userModel';

export interface IUserRepository {
findAllAsync(): Promise<User[]>;
findByIdAsync(id: number): Promise<User | null>;
}

const users: User[] = [
{ id: 1, name: 'Alice', email: '[email protected]', age: 42, createdAt: new Date(), updatedAt: new Date() },
{ id: 2, name: 'Bob', email: '[email protected]', age: 21, createdAt: new Date(), updatedAt: new Date() },
];

export class UserRepository implements IUserRepository {
public async findByIdAsync(id: number) {
export const userRepository = {
findByIdAsync: async (id: number): Promise<User | null> => {
return users.find((user) => user.id === id) || null;
}
},

public async findAllAsync() {
findAllAsync: async (): Promise<User[]> => {
return users || [];
}
}
},
};
28 changes: 17 additions & 11 deletions src/modules/user/userRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import express, { Router } from 'express';
import express, { Request, Response, Router } from 'express';

import { UserController } from '@modules/user/userController';
import { IUserRepository, UserRepository } from '@modules/user/userRepository';
import { IUserService, UserService } from '@modules/user/userService';
import { handleServiceResponse } from '@common/utils/responseHandler';
import { userService } from '@modules/user/userService';

const router: Router = express.Router();
const userRepository: IUserRepository = new UserRepository();
const userService: IUserService = new UserService(userRepository);
const controller: UserController = new UserController(userService);
export const userRouter: Router = (() => {
const router = express.Router();

router.get('/', controller.getAllUsers);
router.get('/:id', controller.getUserById);
router.get('/', async (_req: Request, res: Response) => {
const serviceResponse = await userService.findAll();
handleServiceResponse(serviceResponse, res);
});

export const usersRouter: Router = router;
router.get('/:id', async (req: Request, res: Response) => {
const id = parseInt(req.params.id as string, 10);
const serviceResponse = await userService.findById(id);
handleServiceResponse(serviceResponse, res);
});

return router;
})();
37 changes: 15 additions & 22 deletions src/modules/user/userService.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,31 @@
import { ServiceResponse } from '@common/models/serviceResponse';
import { User } from '@modules/user/userModel';
import { IUserRepository } from '@modules/user/userRepository';
import { userRepository } from '@modules/user/userRepository';
import { logger } from '@src/server';

export interface IUserService {
findAll(): Promise<ServiceResponse<User[] | null>>;
findById(id: number): Promise<ServiceResponse<User | null>>;
}

export class UserService implements IUserService {
private readonly _repository: IUserRepository;

constructor(repository: IUserRepository) {
this._repository = repository;
}

public async findAll() {
export const userService = {
// Retrieves all users from the database
findAll: async (): Promise<ServiceResponse<User[] | null>> => {
try {
const users = await this._repository.findAllAsync();
const users = await userRepository.findAllAsync();
return new ServiceResponse<User[]>(true, 'Users found.', users);
} catch (ex) {
logger.error(ex);
return new ServiceResponse<User[]>(false, 'Error finding all users.', [], ex);
}
}
},

public async findById(id: number) {
// Retrieves a single user by their ID
findById: async (id: number): Promise<ServiceResponse<User | null>> => {
try {
const user = await this._repository.findByIdAsync(id);
if (!user) return new ServiceResponse<User>(false, 'User not found.', null);
const user = await userRepository.findByIdAsync(id);
if (!user) {
return new ServiceResponse<User>(false, 'User not found.', null);
}
return new ServiceResponse<User>(true, 'User found.', user);
} catch (ex) {
logger.error(ex);
logger.error(`Error finding user with id ${id}:`, ex);
return new ServiceResponse<User>(false, 'Error finding user.', null, ex);
}
}
}
},
};
4 changes: 2 additions & 2 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import rateLimiter from '@common/middleware/rateLimiter';
import requestLogger from '@common/middleware/requestLogger';
import { getCorsOrigin } from '@common/utils/envConfig';
import { healthCheckRouter } from '@modules/healthCheck/healthCheckRoutes';
import { usersRouter } from '@modules/user/userRoutes';
import { userRouter } from '@modules/user/userRoutes';

dotenv.config({
path: path.resolve(__dirname, '../.env'),
Expand All @@ -33,7 +33,7 @@ app.use(requestLogger());

// Routes
app.use('/health-check', healthCheckRouter);
app.use('/users', usersRouter);
app.use('/users', userRouter);

// Error handlers
app.use(errorHandler());
Expand Down

0 comments on commit a129fbb

Please sign in to comment.