Skip to content

Commit

Permalink
refactorization and linting
Browse files Browse the repository at this point in the history
  • Loading branch information
ruslanguns committed Aug 10, 2020
1 parent e066ea6 commit 71abea1
Show file tree
Hide file tree
Showing 16 changed files with 95 additions and 74 deletions.
2 changes: 2 additions & 0 deletions src/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Controller, Get } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { AppService } from './app.service';

@ApiTags('Default')
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
Expand Down
6 changes: 3 additions & 3 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PostModule } from './post/post.module';
import { TypeOrmModule } from '@nestjs/typeorm'
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
imports: [
Expand All @@ -18,8 +18,8 @@ import { TypeOrmModule } from '@nestjs/typeorm'
autoLoadEntities: true,
synchronize: true,
logging: true,
logger: 'file'
})
logger: 'file',
}),
],
controllers: [AppController],
providers: [AppService],
Expand Down
2 changes: 1 addition & 1 deletion src/app.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Injectable } from '@nestjs/common';
export class AppService {
getHello(): { message: string } {
return {
message: 'Hello ruslan!'
message: 'Hello ruslan!',
};
}
}
13 changes: 13 additions & 0 deletions src/app.swagger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { INestApplication } from '@nestjs/common';

export const initSwagger = (app: INestApplication) => {
const swaggerConfig = new DocumentBuilder()
.setTitle('MyBlog API')
.setDescription(
'Esta es una API Creada con NestJS con un CRUD básico para un Blog.',
)
.build();
const document = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('/docs', app, document);
};
5 changes: 2 additions & 3 deletions src/helpers/enumToString.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@

/**
* Converts an enum into a String
* @param _enum Enum
* @returns string type
* @gist https://gist.github.com/ruslanguns/d5a6bd9af6bddb77d6b2f2a2fef82748
*/
export const EnumToString = (_enum: object) =>
export const EnumToString = (_enum: object) =>
Object.keys(_enum)
.map(key => _enum[key])
.filter(value => typeof value === 'string') as string[]
.filter(value => typeof value === 'string') as string[];
17 changes: 6 additions & 11 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,15 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger, ValidationPipe } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

import { AppModule } from './app.module';
import { initSwagger } from './app.swagger';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
const logger = new Logger('Bootstrap')
const logger = new Logger('Bootstrap');
const port = 3000;

const swaggerConfig = new DocumentBuilder()
.addBearerAuth()
.setTitle('MyBlog API')
.setDescription('Esta es una API Creada con NestJS con un CRUD básico para un Blog.')
.build();
const document = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('/docs', app, document);
initSwagger(app);

app.useGlobalPipes(
new ValidationPipe({
Expand All @@ -24,6 +19,6 @@ async function bootstrap() {
);

await app.listen(port);
logger.log(`Server is running at ${await app.getUrl()}`)
logger.log(`Server is running at ${await app.getUrl()}`);
}
bootstrap();
14 changes: 10 additions & 4 deletions src/post/dtos/create-post.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { IsNotEmpty, IsString, IsBoolean, IsEnum, IsArray } from 'class-validator';
import {
IsNotEmpty,
IsString,
IsBoolean,
IsEnum,
IsArray,
} from 'class-validator';
import { EnumToString } from '../../helpers/enumToString';
import { PostCategory } from '../enums';

Expand All @@ -17,7 +23,7 @@ export class CreatePostDto {

@IsNotEmpty()
@IsEnum(PostCategory, {
message: `Invalid option. Valids options are ${EnumToString(PostCategory)}`
message: `Invalid option. Valids options are ${EnumToString(PostCategory)}`,
})
category: string;

Expand All @@ -26,5 +32,5 @@ export class CreatePostDto {
tags: string[];

@IsBoolean()
status: boolean;
}
status: boolean;
}
8 changes: 2 additions & 6 deletions src/post/dtos/edit-post.dto.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import { PartialType, OmitType } from '@nestjs/swagger';
import { CreatePostDto } from './create-post.dto';


export class EditPostDto extends PartialType(
OmitType(
CreatePostDto,
['slug'] as const
)
) {}
OmitType(CreatePostDto, ['slug'] as const),
) {}
4 changes: 2 additions & 2 deletions src/post/dtos/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './create-post.dto'
export * from './edit-post.dto'
export * from './create-post.dto';
export * from './edit-post.dto';
2 changes: 1 addition & 1 deletion src/post/entities/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './post.entity'
export * from './post.entity';
29 changes: 17 additions & 12 deletions src/post/entities/post.entity.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,36 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from "typeorm";
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
} from 'typeorm';

@Entity('posts')
export class Post {
@PrimaryGeneratedColumn()
id: number;
@Column({ type: 'text', nullable: false})

@Column({ type: 'text', nullable: false })
slug!: string;

@Column({ type: 'varchar', length: 150 })
title!: string;

@Column({ type: 'varchar', length: 255 })
excerpt?: string;

@Column({ type: 'text' })
content!: string;

@Column({ type: 'varchar', length: 100, nullable: true })
category: string;

@Column({ type: 'simple-array' })
tags: string[];

@Column({ type: 'bool', default: true })
status: boolean;
@CreateDateColumn({type: "timestamp"})

@CreateDateColumn({ type: 'timestamp' })
createdAt: Date;
}
}
2 changes: 1 addition & 1 deletion src/post/enums/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './post-category.enum'
export * from './post-category.enum';
4 changes: 2 additions & 2 deletions src/post/enums/post-category.enum.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export enum PostCategory {
'TECHNOLOGY',
'LIFESTYLE',
'CODING'
}
'CODING',
}
40 changes: 24 additions & 16 deletions src/post/post.controller.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,50 @@
import { Controller, Get, Param, Post, Put, Delete, Body, ParseIntPipe } from '@nestjs/common';
import {
Controller,
Get,
Param,
Post,
Put,
Delete,
Body,
ParseIntPipe,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';

import { PostService } from './post.service';
import { CreatePostDto, EditPostDto } from './dtos';

@ApiTags('Posts')
@Controller('post')
export class PostController {

constructor(private readonly postService: PostService) {}

@Get()
async getMany() {
const data = await this.postService.getMany();
return { data }
return { data };
}

@Get(':id')
async getById(@Param('id', ParseIntPipe) id: number) {
const data = await this.postService.getById(id)
return { data }
const data = await this.postService.getById(id);
return { data };
}

@Post()
async createPost(@Body() dto: CreatePostDto ) {
const data = await this.postService.createOne(dto)
return { message: 'Post created', data}
async createPost(@Body() dto: CreatePostDto) {
const data = await this.postService.createOne(dto);
return { message: 'Post created', data };
}

@Put(':id')
async editOne(
@Param('id') id: number,
@Body() dto: EditPostDto
) {
const data = await this.postService.editOne(id, dto)
return { message: 'Post edited', data }
async editOne(@Param('id') id: number, @Body() dto: EditPostDto) {
const data = await this.postService.editOne(id, dto);
return { message: 'Post edited', data };
}

@Delete(':id')
async deleteOne(@Param('id') id: number) {
const data = await this.postService.deleteOne(id)
return { message: 'Post deleted', data }
const data = await this.postService.deleteOne(id);
return { message: 'Post deleted', data };
}
}
9 changes: 4 additions & 5 deletions src/post/post.module.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

import { PostController } from './post.controller';
import { PostService } from './post.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Post } from './entities';

@Module({
imports: [
TypeOrmModule.forFeature([Post])
],
imports: [TypeOrmModule.forFeature([Post])],
controllers: [PostController],
providers: [PostService]
providers: [PostService],
})
export class PostModule {}
12 changes: 5 additions & 7 deletions src/post/post.service.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { Post } from './entities';
import { CreatePostDto, EditPostDto } from './dtos';

@Injectable()
export class PostService {

constructor(
@InjectRepository(Post)
private readonly postRepository: Repository<Post>
private readonly postRepository: Repository<Post>,
) {}

async getMany() {
return await this.postRepository.find();
}

async getById(id: number) {
const post = await this.postRepository.findOne(id)
if(!post) throw new NotFoundException('Post does not exist')
const post = await this.postRepository.findOne(id);
if (!post) throw new NotFoundException('Post does not exist');
return post;
}

Expand All @@ -30,7 +30,7 @@ export class PostService {
async editOne(id: number, dto: EditPostDto) {
const post = await this.postRepository.findOne(id);

if (!post) throw new NotFoundException('Post does not exist')
if (!post) throw new NotFoundException('Post does not exist');

const editedPost = Object.assign(post, dto);
return await this.postRepository.save(editedPost);
Expand All @@ -39,6 +39,4 @@ export class PostService {
async deleteOne(id: number) {
return await this.postRepository.delete(id);
}


}

0 comments on commit 71abea1

Please sign in to comment.