Skip to content

Commit

Permalink
Post creation works (User mapping bug)
Browse files Browse the repository at this point in the history
  • Loading branch information
devbenho committed May 27, 2024
1 parent e6a80b6 commit 9816199
Show file tree
Hide file tree
Showing 10 changed files with 85 additions and 26 deletions.
Binary file modified server/db.sqlite3
Binary file not shown.
2 changes: 2 additions & 0 deletions server/src/application/post/create/create-post.usecase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ class CreatePostUseCase extends BaseUseCase<
): Promise<PostDetailsResponseDto> {
const post = CreatePostRequest.toEntity(request);
const createdPost = await this._postRepository.createPost(post);
LOGGER.info('Post created successfully');
if (createdPost) {
return PostDetailsResponseDto.fromEntity(createdPost);
}

return {} as PostDetailsResponseDto;
}
}
Expand Down
2 changes: 1 addition & 1 deletion server/src/contracts/dtos/users/user.response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export class UserResponseDto {
public username: string,
public email: string,
public pictureProfile?: string,
) { }
) {}

public static fromEntity(entity: User): UserResponseDto {
return new UserResponseDto(
Expand Down
2 changes: 1 addition & 1 deletion server/src/domain/shared/base.entity.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Nullable } from '@domain/shared/types';

abstract class BaseEntity {
constructor(public id: Nullable<string>) { }
constructor(public id: Nullable<string>) {}
}

export { BaseEntity };
70 changes: 63 additions & 7 deletions server/src/infrastructure/posts/post.mapper.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { LOGGER } from '@/web/rest/logger';
import { Comment, LikePost, Post } from '@domain/entities';
import { POST_STATUS } from '@domain/eums/post-status.enum';
import { CommentMapper } from '@infrastructure/comments/comment.mapper';
Expand All @@ -7,20 +8,75 @@ import { UserMapper } from '@infrastructure/users';

class PostMapper {
public static toDomain(postPersistence: PostPersistence): Post {
const { id, title, content, authorId, author, comments, likes, createdAt, deletedAt, updatedAt, status } = postPersistence;

const {
id,
title,
content,
authorId,
author,
comments = [], // Default to empty array
likes = [], // Default to empty array
createdAt,
deletedAt,
updatedAt,
status,
} = postPersistence;
LOGGER.info('PostMapper.toDomain', postPersistence);
return new Post(
id,
title, content, authorId, UserMapper.toDomain(author),
likes.map(like => LikePostMapper.toDomain(like)),
comments.map(comment => CommentMapper.toDomain(comment)),
title,
content,
authorId,
UserMapper.toDomain(author),
likes.length ? likes.map(like => LikePostMapper.toDomain(like)) : [],
comments.length
? comments.map(comment => CommentMapper.toDomain(comment))
: [],
status as POST_STATUS,
createdAt, updatedAt, deletedAt
createdAt,
updatedAt,
deletedAt,
);
}

public static toPersistence(post: Post): PostPersistence {
return new PostPersistence();
const {
id,
title,
content,
authorId,
author,
comments = [], // Default to empty array
likes = [], // Default to empty array
createdAt,
deletedAt,
status,
} = post;

const postPersistence = new PostPersistence();
if (id != null) {
postPersistence.id = id;
}
postPersistence.title = title;
postPersistence.content = content;
postPersistence.authorId = authorId;
postPersistence.author = UserMapper.toPersistence(author);

if (post.comments.length) {
postPersistence.comments = comments.map(comment =>
CommentMapper.toPersistence(comment),
);
}
if (post.likes.length) {
postPersistence.likes = likes.map(like =>
LikePostMapper.toPersistence(like),
);
}

postPersistence.createdAt = createdAt;
postPersistence.deletedAt = deletedAt;
postPersistence.status = status as POST_STATUS;
return postPersistence;
}
}

Expand Down
2 changes: 2 additions & 0 deletions server/src/infrastructure/posts/post.repository.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { Post } from '@domain/entities';
import { IPostRepository } from '@domain/repositories/post.repository';
import { PostPersistence } from './post.persistence';
import { PostMapper } from './post.mapper';
import { LOGGER } from '@/web/rest/logger';

@injectable()
export class PostRepository implements IPostRepository {
Expand All @@ -27,6 +28,7 @@ export class PostRepository implements IPostRepository {
async createPost(post: Post): Promise<Post> {
const postPersistence = PostMapper.toPersistence(post);
const createdPost = await this._repository.save(postPersistence);

return PostMapper.toDomain(createdPost);
}

Expand Down
7 changes: 3 additions & 4 deletions server/src/infrastructure/shared/ioc/inversify.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { Container } from 'inversify';
import { TYPES } from './types';
import { JwtService } from '@infrastructure/shared/jwt/jwt.service.impl';
import { UserMapper, UserRepository } from '@infrastructure/users';

import { HasherService } from '@infrastructure/shared/hasher/hasher.service';
import { AuthController } from '@/web/rest/controllers';
import ApplicationRouter from '@/web/rest/routes';
Expand All @@ -16,7 +15,8 @@ import { PostRepository } from '@infrastructure/posts';
import { CreatePostUseCase } from '@application/post';

const container = new Container();
// Bind the extrernal dependencies

// Bind the external dependencies
container.bind(TYPES.IJwtService).to(JwtService);
container.bind(TYPES.IHasherService).to(HasherService);
container.bind(TYPES.IUserMapper).to(UserMapper);
Expand All @@ -28,7 +28,6 @@ container.bind(TYPES.IPostRepository).to(PostRepository);
// Inject input ports
container.bind(TYPES.ILoginInputPort).to(LoginUseCase);
container.bind(TYPES.IRegisterInputPort).to(RegisterUsecase);

container.bind(TYPES.ICreatePostInputPort).to(CreatePostUseCase);

// Bind the controllers
Expand All @@ -38,7 +37,7 @@ container.bind(TYPES.IPostController).to(PostsController);
// Bind ApplicationRouter
container.bind<ApplicationRouter>(ApplicationRouter).to(ApplicationRouter);

// bind the datastore
// Bind the datastore
container.bind<DataSource>(DataSource).toConstantValue(appDataSource);

export { container };
6 changes: 3 additions & 3 deletions server/src/web/process.log
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{"level":30,"time":1716762870073,"msg":"Application is running on port 2105 🚀"}
{"level":30,"time":1716762870077,"msg":"Environment: development"}
{"level":30,"time":1716762870107,"msg":"Data source initialized"}
{"level":30,"time":1716846525660,"msg":"Application is running on port 2105 🚀"}
{"level":30,"time":1716846525664,"msg":"Environment: development"}
{"level":30,"time":1716846525693,"msg":"Data source initialized"}
3 changes: 1 addition & 2 deletions server/src/web/rest/controllers/posts.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { TYPES } from '@infrastructure/shared/ioc/types';
import { inject, injectable } from 'inversify';
import { ExpressHandler } from '../infrastucture/express-handler';
import BaseController from './base.controller';
import { LOGGER } from '../logger';
import { POST_STATUS } from '@domain/eums/post-status.enum';
import { log } from 'console';

@injectable()
export class PostsController implements BaseController {
Expand All @@ -27,7 +27,6 @@ export class PostsController implements BaseController {

public create: ExpressHandler<CreatePostRequest, CreatePostResponseDto> =
async (req, res) => {
LOGGER.info('PostsController.create');
const { title, content } = req.body;
if (!title || !content) {
return res.status(400).json({});
Expand Down
17 changes: 9 additions & 8 deletions server/src/web/rest/middlewares/login.mw.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { VerifyErrors } from 'jsonwebtoken';
import { ExpressHandler } from '../infrastucture/express-handler';
import { JwtService } from '../../../infrastructure/shared/jwt/jwt.service.impl';
import { UserRepository } from '@infrastructure/users';
import { container } from '@infrastructure/shared/ioc/inversify.config';
Expand All @@ -9,14 +8,15 @@ import {
} from '@contracts/errors/unauthorized.error';
import { DataSource } from 'typeorm';
import { LOGGER } from '../logger';
import { log } from 'console';
import { JwtPayload } from '@contracts/services/IJwt';
import { NextFunction, Request, Response } from 'express';
import { ExpressHandler } from '../infrastucture/express-handler';

class AuthMiddleware {
public static jwtParseMiddleware: ExpressHandler<any, any> = async (
req,
res,
next,
req: Request,
res: Response,
next: NextFunction,
) => {
const jwtService = new JwtService();
const userRepository = new UserRepository(container.get(DataSource));
Expand Down Expand Up @@ -46,13 +46,14 @@ class AuthMiddleware {

res.locals.userId = user.id;
res.locals.user = user;
LOGGER.info(`Request after auth middleware: ${JSON.stringify(req.body)}`);
return next();
};

public static enforceJwtMiddleware: ExpressHandler<any, any> = async (
_,
res,
next,
_: Request,
res: Response,
next: NextFunction,
) => {
if (!res.locals.userId) {
return res.sendStatus(401);
Expand Down

0 comments on commit 9816199

Please sign in to comment.