Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: clean code #50

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 18 additions & 19 deletions src/article/article.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {Get, Post, Body, Put, Delete, Query, Param, Controller} from '@nestjs/common';
import { Request } from 'express';
import { ArticleService } from './article.service';
import { CreateArticleDto, CreateCommentDto } from './dto';
import { ArticlesRO, ArticleRO } from './article.interface';
Expand All @@ -22,42 +21,42 @@ export class ArticleController {
@ApiOperation({ summary: 'Get all articles' })
@ApiResponse({ status: 200, description: 'Return all articles.'})
@Get()
async findAll(@Query() query): Promise<ArticlesRO> {
return await this.articleService.findAll(query);
findAll(@Query() query): Promise<ArticlesRO> {
return this.articleService.findAll(query);
}


@ApiOperation({ summary: 'Get article feed' })
@ApiResponse({ status: 200, description: 'Return article feed.'})
@ApiResponse({ status: 403, description: 'Forbidden.' })
@Get('feed')
async getFeed(@User('id') userId: number, @Query() query): Promise<ArticlesRO> {
return await this.articleService.findFeed(userId, query);
getFeed(@User('id') userId: number, @Query() query): Promise<ArticlesRO> {
return this.articleService.findFeed(userId, query);
}

@Get(':slug')
async findOne(@Param('slug') slug): Promise<ArticleRO> {
return await this.articleService.findOne({slug});
findOne(@Param('slug') slug): Promise<ArticleRO> {
return this.articleService.findOne({slug});
}

@Get(':slug/comments')
async findComments(@Param('slug') slug): Promise<CommentsRO> {
return await this.articleService.findComments(slug);
findComments(@Param('slug') slug): Promise<CommentsRO> {
return this.articleService.findComments(slug);
}

@ApiOperation({ summary: 'Create article' })
@ApiResponse({ status: 201, description: 'The article has been successfully created.'})
@ApiResponse({ status: 403, description: 'Forbidden.' })
@Post()
async create(@User('id') userId: number, @Body('article') articleData: CreateArticleDto) {
create(@User('id') userId: number, @Body('article') articleData: CreateArticleDto) {
return this.articleService.create(userId, articleData);
}

@ApiOperation({ summary: 'Update article' })
@ApiResponse({ status: 201, description: 'The article has been successfully updated.'})
@ApiResponse({ status: 403, description: 'Forbidden.' })
@Put(':slug')
async update(@Param() params, @Body('article') articleData: CreateArticleDto) {
update(@Param() params, @Body('article') articleData: CreateArticleDto) {
// Todo: update slug also when title gets changed
return this.articleService.update(params.slug, articleData);
}
Expand All @@ -66,16 +65,16 @@ export class ArticleController {
@ApiResponse({ status: 201, description: 'The article has been successfully deleted.'})
@ApiResponse({ status: 403, description: 'Forbidden.' })
@Delete(':slug')
async delete(@Param() params) {
delete(@Param() params) {
return this.articleService.delete(params.slug);
}

@ApiOperation({ summary: 'Create comment' })
@ApiResponse({ status: 201, description: 'The comment has been successfully created.'})
@ApiResponse({ status: 403, description: 'Forbidden.' })
@Post(':slug/comments')
async createComment(@Param('slug') slug, @Body('comment') commentData: CreateCommentDto) {
return await this.articleService.addComment(slug, commentData);
createComment(@Param('slug') slug, @Body('comment') commentData: CreateCommentDto) {
return this.articleService.addComment(slug, commentData);
}

@ApiOperation({ summary: 'Delete comment' })
Expand All @@ -91,16 +90,16 @@ export class ArticleController {
@ApiResponse({ status: 201, description: 'The article has been successfully favorited.'})
@ApiResponse({ status: 403, description: 'Forbidden.' })
@Post(':slug/favorite')
async favorite(@User('id') userId: number, @Param('slug') slug) {
return await this.articleService.favorite(userId, slug);
favorite(@User('id') userId: number, @Param('slug') slug) {
return this.articleService.favorite(userId, slug);
}

@ApiOperation({ summary: 'Unfavorite article' })
@ApiResponse({ status: 201, description: 'The article has been successfully unfavorited.'})
@ApiResponse({ status: 403, description: 'Forbidden.' })
@Delete(':slug/favorite')
async unFavorite(@User('id') userId: number, @Param('slug') slug) {
return await this.articleService.unFavorite(userId, slug);
unFavorite(@User('id') userId: number, @Param('slug') slug) {
return this.articleService.unFavorite(userId, slug);
}

}
}
46 changes: 22 additions & 24 deletions src/article/article.service.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getRepository, DeleteResult } from 'typeorm';
import { ArticleEntity } from './article.entity';
import { Comment } from './comment.entity';
import { UserEntity } from '../user/user.entity';
import { FollowsEntity } from '../profile/follows.entity';
import { CreateArticleDto } from './dto';
import {Injectable} from '@nestjs/common';
import {InjectRepository} from '@nestjs/typeorm';
import {Repository, getRepository, DeleteResult} from 'typeorm';
import {ArticleEntity} from './article.entity';
import {Comment} from './comment.entity';
import {UserEntity} from '../user/user.entity';
import {FollowsEntity} from '../profile/follows.entity';
import {CreateArticleDto} from './dto';

import {ArticleRO, ArticlesRO, CommentsRO} from './article.interface';

const slug = require('slug');

@Injectable()
Expand All @@ -21,7 +22,8 @@ export class ArticleService {
private readonly userRepository: Repository<UserEntity>,
@InjectRepository(FollowsEntity)
private readonly followsRepository: Repository<FollowsEntity>
) {}
) {
}

async findAll(query): Promise<ArticlesRO> {

Expand All @@ -32,18 +34,18 @@ export class ArticleService {
qb.where("1 = 1");

if ('tag' in query) {
qb.andWhere("article.tagList LIKE :tag", { tag: `%${query.tag}%` });
qb.andWhere("article.tagList LIKE :tag", {tag: `%${query.tag}%`});
}

if ('author' in query) {
const author = await this.userRepository.findOne({username: query.author});
qb.andWhere("article.authorId = :id", { id: author.id });
qb.andWhere("article.authorId = :id", {id: author.id});
}

if ('favorited' in query) {
const author = await this.userRepository.findOne({username: query.favorited});
const ids = author.favorites.map(el => el.id);
qb.andWhere("article.authorId IN (:ids)", { ids });
qb.andWhere("article.authorId IN (:ids)", {ids});
}

qb.orderBy('article.created', 'DESC');
Expand All @@ -64,7 +66,7 @@ export class ArticleService {
}

async findFeed(userId: number, query): Promise<ArticlesRO> {
const _follows = await this.followsRepository.find( {followerId: userId});
const _follows = await this.followsRepository.find({followerId: userId});

if (!(Array.isArray(_follows) && _follows.length > 0)) {
return {articles: [], articlesCount: 0};
Expand All @@ -74,7 +76,7 @@ export class ArticleService {

const qb = await getRepository(ArticleEntity)
.createQueryBuilder('article')
.where('article.authorId IN (:ids)', { ids });
.where('article.authorId IN (:ids)', {ids});

qb.orderBy('article.created', 'DESC');

Expand Down Expand Up @@ -120,12 +122,10 @@ export class ArticleService {
if (deleteIndex >= 0) {
const deleteComments = article.comments.splice(deleteIndex, 1);
await this.commentRepository.delete(deleteComments[0].id);
article = await this.articleRepository.save(article);
return {article};
} else {
return {article};
article = await this.articleRepository.save(article);
}

return {article};
}

async favorite(id: number, slug: string): Promise<ArticleRO> {
Expand Down Expand Up @@ -168,7 +168,6 @@ export class ArticleService {
}

async create(userId: number, articleData: CreateArticleDto): Promise<ArticleEntity> {

let article = new ArticleEntity();
article.title = articleData.title;
article.description = articleData.description;
Expand All @@ -178,24 +177,23 @@ export class ArticleService {

const newArticle = await this.articleRepository.save(article);

const author = await this.userRepository.findOne({ where: { id: userId }, relations: ['articles'] });
const author = await this.userRepository.findOne({where: {id: userId}, relations: ['articles']});
author.articles.push(article);

await this.userRepository.save(author);

return newArticle;

}

async update(slug: string, articleData: any): Promise<ArticleRO> {
let toUpdate = await this.articleRepository.findOne({ slug: slug});
let toUpdate = await this.articleRepository.findOne({slug: slug});
let updated = Object.assign(toUpdate, articleData);
const article = await this.articleRepository.save(updated);
return {article};
}

async delete(slug: string): Promise<DeleteResult> {
return await this.articleRepository.delete({ slug: slug});
delete(slug: string): Promise<DeleteResult> {
return this.articleRepository.delete({slug: slug});
}

slugify(title: string) {
Expand Down
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ async function bootstrap() {

await app.listen(3000);
}
bootstrap();
bootstrap();
15 changes: 7 additions & 8 deletions src/profile/profile.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Get, Post, Delete, Param, Controller } from '@nestjs/common';
import { Request } from 'express';
import { ProfileService } from './profile.service';
import { ProfileRO } from './profile.interface';
import { User } from '../user/user.decorator';
Expand All @@ -16,18 +15,18 @@ export class ProfileController {
constructor(private readonly profileService: ProfileService) {}

@Get(':username')
async getProfile(@User('id') userId: number, @Param('username') username: string): Promise<ProfileRO> {
return await this.profileService.findProfile(userId, username);
getProfile(@User('id') userId: number, @Param('username') username: string): Promise<ProfileRO> {
return this.profileService.findProfile(userId, username);
}

@Post(':username/follow')
async follow(@User('email') email: string, @Param('username') username: string): Promise<ProfileRO> {
return await this.profileService.follow(email, username);
follow(@User('email') email: string, @Param('username') username: string): Promise<ProfileRO> {
return this.profileService.follow(email, username);
}

@Delete(':username/follow')
async unFollow(@User('id') userId: number, @Param('username') username: string): Promise<ProfileRO> {
return await this.profileService.unFollow(userId, username);
unFollow(@User('id') userId: number, @Param('username') username: string): Promise<ProfileRO> {
return this.profileService.unFollow(userId, username);
}

}
}
4 changes: 2 additions & 2 deletions src/profile/profile.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export class ProfileService {
private readonly followsRepository: Repository<FollowsEntity>
) {}

async findAll(): Promise<UserEntity[]> {
return await this.userRepository.find();
findAll(): Promise<UserEntity[]> {
return this.userRepository.find();
}

async findOne(options?: DeepPartial<UserEntity>): Promise<ProfileRO> {
Expand Down
6 changes: 3 additions & 3 deletions src/tag/tag.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ export class TagController {
constructor(private readonly tagService: TagService) {}

@Get()
async findAll(): Promise<TagEntity[]> {
return await this.tagService.findAll();
findAll(): Promise<TagEntity[]> {
return this.tagService.findAll();
}

}
}
5 changes: 2 additions & 3 deletions src/user/user.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Get, Post, Body, Put, Delete, Param, Controller, UsePipes } from '@nestjs/common';
import { Request } from 'express';
import { UserService } from './user.service';
import { UserRO } from './user.interface';
import { CreateUserDto, UpdateUserDto, LoginUserDto } from './dto';
Expand Down Expand Up @@ -35,8 +34,8 @@ export class UserController {
}

@Delete('users/:slug')
async delete(@Param() params) {
return await this.userService.delete(params.slug);
delete(@Param() params) {
return this.userService.delete(params.slug);
}

@UsePipes(new ValidationPipe())
Expand Down
9 changes: 4 additions & 5 deletions src/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,10 @@ export class UserService {
if (user) {
const errors = {username: 'Username and email must be unique.'};
throw new HttpException({message: 'Input data validation failed', errors}, HttpStatus.BAD_REQUEST);

}

// create new user
let newUser = new UserEntity();
const newUser = new UserEntity();
newUser.username = username;
newUser.email = email;
newUser.password = password;
Expand All @@ -77,11 +76,11 @@ export class UserService {
delete toUpdate.favorites;

let updated = Object.assign(toUpdate, dto);
return await this.userRepository.save(updated);
return this.userRepository.save(updated);
}

async delete(email: string): Promise<DeleteResult> {
return await this.userRepository.delete({ email: email});
delete(email: string): Promise<DeleteResult> {
return this.userRepository.delete({ email: email});
}

async findById(id: number): Promise<UserRO>{
Expand Down
Loading