Skip to content

Commit

Permalink
renames
Browse files Browse the repository at this point in the history
  • Loading branch information
mariovyord committed Dec 22, 2023
1 parent 71c372e commit dc5a7fe
Show file tree
Hide file tree
Showing 10 changed files with 53 additions and 64 deletions.
18 changes: 9 additions & 9 deletions src/features/article/article-service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { IFullQuery, parseQueryToMongoParams } from "../../utils/parse-query";
import * as articleRepository from "./article-repository";
import { ArticleEntity, ICreateArticleData, IPatchArticleData } from "./article-types";
import { ArticleDto, ICreateArticleData, IPatchArticleData } from "./article-types";

export async function getAll(query: IFullQuery): Promise<ArticleEntity[] | number> {
export async function getAll(query: IFullQuery): Promise<ArticleDto[] | number> {
const parsedQuery = parseQueryToMongoParams(query);

if (parsedQuery.count) {
Expand All @@ -11,10 +11,10 @@ export async function getAll(query: IFullQuery): Promise<ArticleEntity[] | numbe

const articles = await articleRepository.findArticlesByQuery(parsedQuery);

return articles.map((x) => new ArticleEntity(x));
return articles.map((x) => new ArticleDto(x));
}

export async function getOne(id: string, query: any): Promise<ArticleEntity | null> {
export async function getOne(id: string, query: any): Promise<ArticleDto | null> {
let populate = "";
let limitPopulate = "";

Expand All @@ -32,17 +32,17 @@ export async function getOne(id: string, query: any): Promise<ArticleEntity | nu
throw new Error("Not found");
}

return new ArticleEntity(article);
return new ArticleDto(article);
}

export async function create(data: ICreateArticleData): Promise<ArticleEntity> {
export async function create(data: ICreateArticleData): Promise<ArticleDto> {
const article = await articleRepository.createArticle(data);
return new ArticleEntity(article);
return new ArticleDto(article);
}

const ALLOWED_UPDATE_FIELDS = ["title", "content"];

export async function update(id: string, userId: string, data: IPatchArticleData): Promise<ArticleEntity> {
export async function update(id: string, userId: string, data: IPatchArticleData): Promise<ArticleDto> {
const article = await articleRepository.findArticleById(id);

if (article === null) throw new Error("Article not found");
Expand All @@ -56,7 +56,7 @@ export async function update(id: string, userId: string, data: IPatchArticleData

await article.save();

return new ArticleEntity(article);
return new ArticleDto(article);
}

export async function remove(id: string, userId: string): Promise<void> {
Expand Down
8 changes: 4 additions & 4 deletions src/features/article/article-types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ObjectId } from "mongodb";
import { IUser, UserEntity } from "../user/user-types";
import { IUser, UserDto } from "../user/user-types";
import { isValidObjectId } from "mongoose";

export interface IArticle {
Expand All @@ -20,11 +20,11 @@ export type IPatchArticleData = Pick<IArticle, "title" | "content">;
/**
* Represents a Public Article with limited information.
*/
export class ArticleEntity {
export class ArticleDto {
id: string;
title: string;
content: string;
owner: UserEntity | string;
owner: UserDto | string;
createdAt: Date;
updatedAt: Date;

Expand All @@ -38,7 +38,7 @@ export class ArticleEntity {
if (isValidObjectId(article.owner)) {
this.owner = (article.owner as ObjectId).toString();
} else {
this.owner = new UserEntity(article.owner as IUser);
this.owner = new UserDto(article.owner as IUser);
}
}
}
18 changes: 9 additions & 9 deletions src/features/comment/comment-service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { IFullQuery, parseQueryToMongoParams } from "../../utils/parse-query";
import * as commentRepository from "./comment-repository";
import { CommentEntity, ICreateCommentData, IPatchCommentData } from "./comment-types";
import { CommentDto, ICreateCommentData, IPatchCommentData } from "./comment-types";

export async function getAllComments(query: IFullQuery): Promise<CommentEntity[] | number> {
export async function getAllComments(query: IFullQuery): Promise<CommentDto[] | number> {
const parsedQuery = parseQueryToMongoParams(query);

if (parsedQuery.count) {
Expand All @@ -11,10 +11,10 @@ export async function getAllComments(query: IFullQuery): Promise<CommentEntity[]

const comments = await commentRepository.findCommentsByQuery(parsedQuery);

return comments.map((x) => new CommentEntity(x));
return comments.map((x) => new CommentDto(x));
}

export async function getOneComment(id: string, query: any): Promise<CommentEntity | null> {
export async function getOneComment(id: string, query: any): Promise<CommentDto | null> {
let populate = "";
let limitPopulate = "";

Expand All @@ -32,17 +32,17 @@ export async function getOneComment(id: string, query: any): Promise<CommentEnti
throw new Error("Not found");
}

return new CommentEntity(comment);
return new CommentDto(comment);
}

export async function createComment(data: ICreateCommentData): Promise<CommentEntity> {
export async function createComment(data: ICreateCommentData): Promise<CommentDto> {
const comment = await commentRepository.createComment(data);
return new CommentEntity(comment);
return new CommentDto(comment);
}

const ALLOWED_UPDATE_FIELDS = ["content"];

export async function updateComment(id: string, userId: string, data: IPatchCommentData): Promise<CommentEntity> {
export async function updateComment(id: string, userId: string, data: IPatchCommentData): Promise<CommentDto> {
const comment = await commentRepository.findCommentById(id);

if (comment === null) throw new Error("Comment not found");
Expand All @@ -56,7 +56,7 @@ export async function updateComment(id: string, userId: string, data: IPatchComm

await comment.save();

return new CommentEntity(comment);
return new CommentDto(comment);
}

export async function deleteComment(id: string, userId: string): Promise<void> {
Expand Down
8 changes: 4 additions & 4 deletions src/features/comment/comment-types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ObjectId, WithId } from "mongodb";
import { isValidObjectId } from "mongoose";
import { IUser, UserEntity } from "../user/user-types";
import { IUser, UserDto } from "../user/user-types";

export interface IComment {
_id: ObjectId;
Expand All @@ -19,10 +19,10 @@ export type IPatchCommentData = Pick<IComment, "content">;
/**
* Represents a Public Comment with limited information.
*/
export class CommentEntity {
export class CommentDto {
id: string;
content: string;
owner: UserEntity | string;
owner: UserDto | string;
parent: string;
article: string;
createdAt: Date;
Expand All @@ -39,7 +39,7 @@ export class CommentEntity {
if (isValidObjectId(comment.owner)) {
this.owner = (comment.owner as ObjectId).toString();
} else {
this.owner = new UserEntity(comment.owner as IUser);
this.owner = new UserDto(comment.owner as IUser);
}
}
}
4 changes: 2 additions & 2 deletions src/features/user/user-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import * as userService from "./user-service";
import { NextFunction, Request, Response } from "express";
import { AppError } from "../../utils/app-error";
import { HttpStatusCode } from "../../utils/http-status-code";
import { IUserLocal, UserEntity } from "./user-types";
import { IUserLocal, UserDto } from "./user-types";

const authCookieName = "jwt";
const authCookieOptions = {
Expand Down Expand Up @@ -86,7 +86,7 @@ export function updateUser() {
}

const userData = req.body;
const updatedUser: UserEntity = await userService.updateUser(user.id, userData);
const updatedUser: UserDto = await userService.updateUser(user.id, userData);

return res.json({
code: HttpStatusCode.OK,
Expand Down
2 changes: 1 addition & 1 deletion src/features/user/user-repository.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import User from "./user-schema";
import { ISignUpUserData, UserEntity } from "./user-types";
import { ISignUpUserData, UserDto } from "./user-types";

export async function findOneByUsername(username: string | undefined) {
if (!username) return null;
Expand Down
18 changes: 9 additions & 9 deletions src/features/user/user-service.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import jwt from "jsonwebtoken";
import getConfig from "../../config/get-config";
import { IUserLocal, ISignUpUserData, UserEntity, IUpdateUserData } from "./user-types";
import { IUserLocal, ISignUpUserData, UserDto, IUpdateUserData } from "./user-types";
import * as userRepository from "./user-repository";

export async function signUp(userData: ISignUpUserData): Promise<[string, UserEntity]> {
export async function signUp(userData: ISignUpUserData): Promise<[string, UserDto]> {
const existing = await userRepository.findOneByUsername(userData.username);

if (existing) {
Expand All @@ -13,10 +13,10 @@ export async function signUp(userData: ISignUpUserData): Promise<[string, UserEn
const user = await userRepository.createUser(userData);
const token = await createToken(user.id);

return [token, new UserEntity(user)];
return [token, new UserDto(user)];
}

export async function signIn(username: string, password: string): Promise<[string, UserEntity]> {
export async function signIn(username: string, password: string): Promise<[string, UserDto]> {
const user = await userRepository.findOneByPassword(username, password);

if (!user) {
Expand All @@ -25,7 +25,7 @@ export async function signIn(username: string, password: string): Promise<[strin

const token = await createToken(user.id);

return [token, new UserEntity(user)];
return [token, new UserDto(user)];
}

async function createToken(id: string) {
Expand All @@ -40,19 +40,19 @@ async function createToken(id: string) {
});
}

export async function getUser(userData: IUserLocal): Promise<UserEntity> {
export async function getUser(userData: IUserLocal): Promise<UserDto> {
const user = await userRepository.findOneById(userData.id);

if (!user) {
throw new Error("Not found");
}

return new UserEntity(user);
return new UserDto(user);
}

const ALLOWED_UPDATE_FIELDS = ["firstName", "lastName"];

export async function updateUser(userId: string, userData: Partial<IUpdateUserData>): Promise<UserEntity> {
export async function updateUser(userId: string, userData: Partial<IUpdateUserData>): Promise<UserDto> {
const user = await userRepository.findOneById(userId);

if (user === null || user._id.toString() !== userId) {
Expand All @@ -68,7 +68,7 @@ export async function updateUser(userId: string, userData: Partial<IUpdateUserDa
// mongoose will auto-update updatedAt field
await user.save();

return new UserEntity(user);
return new UserDto(user);
}

export async function updatePassword(userId: string, oldPassword: string, newPassword: string) {
Expand Down
2 changes: 1 addition & 1 deletion src/features/user/user-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export interface IUpdateUserData {
/**
* Represents a Public User with limited information.
*/
export class UserEntity {
export class UserDto {
id: string;
username: string;
firstName: string;
Expand Down
35 changes: 12 additions & 23 deletions src/middleware/error-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,20 @@ import { IJsonResponse } from "../utils/json-response";

const authCookie = "jwt";

// eslint-disable-next-line no-unused-vars
const errorMiddleware =
() =>
(
err: AppError,
req: Request,
res: Response<IJsonResponse>,
next: NextFunction
) => {
const {
statusCode = HttpStatusCode.INTERNAL_SERVER_ERROR,
message = "Something went wrong",
} = err;
const errorMiddleware = () => (err: AppError, req: Request, res: Response<IJsonResponse>, next: NextFunction) => {
const { statusCode = HttpStatusCode.INTERNAL_SERVER_ERROR, message = "Something went wrong" } = err;

console.error(`Code: ${statusCode}; Error: ${message}`);
console.error(`Code: ${statusCode}; Error: ${message}`);

if (statusCode === HttpStatusCode.FORBIDDEN) {
res.clearCookie(authCookie);
}
if (statusCode === HttpStatusCode.FORBIDDEN) {
res.clearCookie(authCookie);
}

res.status(statusCode).json({
code: statusCode,
message: message,
data: null,
});
};
res.status(statusCode).json({
code: statusCode,
message: message,
data: null,
});
};

export default errorMiddleware;
4 changes: 2 additions & 2 deletions src/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@
"oneOf": [
{
"type": "object",
"$ref": "#/components/schemas/UserEntity"
"$ref": "#/components/schemas/UserDto"
},
{
"type": "null"
Expand Down Expand Up @@ -403,7 +403,7 @@
}
}
},
"UserEntity": {
"UserDto": {
"type": "object",
"properties": {
"id": {
Expand Down

0 comments on commit dc5a7fe

Please sign in to comment.