Skip to content

Commit

Permalink
Merge pull request #3 from bodyduardU/connect_mongo_nestjs
Browse files Browse the repository at this point in the history
Connect mongo nestjs
  • Loading branch information
bodyduardU authored Mar 9, 2023
2 parents 7d97878 + d2770c3 commit 8688020
Show file tree
Hide file tree
Showing 20 changed files with 356 additions and 4 deletions.
22 changes: 18 additions & 4 deletions nestjs/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,24 @@
import { Module } from '@nestjs/common';
import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

import { CatsModule } from './cats/cats.module';
import { logger } from './common/middleware/logger.middleware';
import { CatsController } from './cats/cats.controller';
import { MongooseModule } from '@nestjs/mongoose';
import { TodoModule } from './todo/todo.module';
@Module({
imports: [],
imports: [CatsModule, MongooseModule.forRoot('mongodb://localhost/nest'), TodoModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(logger)
.exclude(
{ path: 'cats', method: RequestMethod.GET },
{ path: 'cats', method: RequestMethod.POST },
)
.forRoutes(CatsController);
}
}
18 changes: 18 additions & 0 deletions nestjs/src/cats/cats.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CatsController } from './cats.controller';

describe('CatsController', () => {
let controller: CatsController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [CatsController],
}).compile();

controller = module.get<CatsController>(CatsController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
65 changes: 65 additions & 0 deletions nestjs/src/cats/cats.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import {
Controller,
Get,
Req,
Res,
Post,
Body,
HttpStatus,
HttpException,
ForbiddenException,
Param,
ParseIntPipe,
} from '@nestjs/common';

import { CatsService } from './cats.service';
import { CreateCatDto } from './create-cat.dto';
import { Cat } from 'src/interfaces/cat.interface';
import { Query } from '@nestjs/common/decorators';
import { UsePipes } from '@nestjs/common/decorators/core/use-pipes.decorator';

@Controller('cats')
export class CatsController {
constructor(private catsService: CatsService) {}
@Post()
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}

@Get(':id')
async findOne(
@Param(
'id',
new ParseIntPipe({ errorHttpStatusCode: HttpStatus.NOT_ACCEPTABLE }),
)
id: number,
) {
return this.catsService.findAll();
}
// @Get()
// async xxx() {
// try {
// await this.catsService.findAll();
// } catch (error) {
// throw new HttpException(
// {
// status: HttpStatus.FORBIDDEN,
// error: 'This is a custom message',
// },
// HttpStatus.FORBIDDEN,
// {
// cause: error,
// },
// );
// }
// }
// @Get()
// async findAll() {
// throw new ForbiddenException();
// }

// @Get()
// async findAll(): Promise<Cat[]> {
// return this.catsService.findAll();
// }
}
21 changes: 21 additions & 0 deletions nestjs/src/cats/cats.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';
import { MongooseModule } from '@nestjs/mongoose';
import { Cat, CatSchema } from 'src/schemas/cat.schema';

@Module({
imports: [
MongooseModule.forFeature([
{
name: Cat.name,
schema: CatSchema,
},
]),
],
controllers: [CatsController],
providers: [CatsService],
})
export class CatsModule {
constructor(private catsService: CatsService) {}
}
18 changes: 18 additions & 0 deletions nestjs/src/cats/cats.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CatsService } from './cats.service';

describe('CatsService', () => {
let service: CatsService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [CatsService],
}).compile();

service = module.get<CatsService>(CatsService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});
});
16 changes: 16 additions & 0 deletions nestjs/src/cats/cats.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Injectable } from '@nestjs/common';
// import { Cat } from 'src/interfaces/cat.interface';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Cat, CatDocument } from 'src/schemas/cat.schema';
import { CreateCatDto } from './create-cat.dto';

@Injectable()
export class CatsService {
private readonly cats: Cat[] = [];
async create(createCatDto: CreateCatDto) {}

findAll(): Cat[] {
return this.cats;
}
}
10 changes: 10 additions & 0 deletions nestjs/src/cats/create-cat.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { IsString, IsInt } from 'class-validator';

export class CreateCatDto {
@IsString()
name: string;
@IsInt()
age: number;
@IsString()
breed: string;
}
7 changes: 7 additions & 0 deletions nestjs/src/cats/forbidden.exception.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { HttpStatus, HttpException } from '@nestjs/common';

export class ForbiddenException extends HttpException {
constructor() {
super('Forbidden', HttpStatus.FORBIDDEN);
}
}
6 changes: 6 additions & 0 deletions nestjs/src/common/middleware/logger.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Request, Response, NextFunction } from 'express';

export function logger(req: Request, res: Response, next: NextFunction) {
console.log(`Request...`);
next();
}
5 changes: 5 additions & 0 deletions nestjs/src/interfaces/cat.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface Cat {
name: string;
age: number;
breed: string;
}
16 changes: 16 additions & 0 deletions nestjs/src/schemas/cat.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';

export type CatDocument = HydratedDocument<Cat>;

@Schema()
export class Cat {
@Prop()
name: string;
@Prop()
age: number;
@Prop()
breed: string;
}

export const CatSchema = SchemaFactory.createForClass(Cat);
4 changes: 4 additions & 0 deletions nestjs/src/todo/dto/base-todo.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export class BaseTodoDto {
title: string;
description?: string;
}
3 changes: 3 additions & 0 deletions nestjs/src/todo/dto/create-todo.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { BaseTodoDto } from './base-todo.dto';

export class CreateTodoDto extends BaseTodoDto {}
5 changes: 5 additions & 0 deletions nestjs/src/todo/dto/update-todo.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { BaseTodoDto } from './base-todo.dto';

export class UpdateTodoDto extends BaseTodoDto {
completedAt: Date;
}
20 changes: 20 additions & 0 deletions nestjs/src/todo/schemas/schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Document } from 'mongoose';
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';

export type TodoDocument = Todo & Document;

@Schema()
export class Todo {
@Prop({ required: true })
title: string;
@Prop()
description?: string;
@Prop()
completeAt?: Date;
@Prop()
createAt: Date;
@Prop()
deleteAt?: Date;
}

export const TodoSchema = SchemaFactory.createForClass(Todo);
18 changes: 18 additions & 0 deletions nestjs/src/todo/todo.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { TodoController } from './todo.controller';

describe('TodoController', () => {
let controller: TodoController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [TodoController],
}).compile();

controller = module.get<TodoController>(TodoController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
37 changes: 37 additions & 0 deletions nestjs/src/todo/todo.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import {
Post,
Controller,
Body,
Put,
Delete,
Get,
Param,
} from '@nestjs/common';
import { UpdateTodoDto } from './dto/update-todo.dto';
import { CreateTodoDto } from './dto/create-todo.dto';
import { TodoService } from './todo.service';

@Controller('todo')
export class TodoController {
constructor(private readonly service: TodoService) {}
@Get()
async index() {
return await this.service.findAll();
}
@Get(':id')
async find(@Param('id') id: string) {
return await this.service.findOne(id);
}
@Post()
async create(@Body() createTodoDto: CreateTodoDto) {
return await this.service.create(createTodoDto);
}
@Put(':id')
async update(@Param('id') id: string, @Body() UpdateTodoDto: UpdateTodoDto) {
return await this.service.update(id, UpdateTodoDto);
}
@Delete(':id')
async delete(@Param('id') id: string) {
return await this.service.delete(id);
}
}
15 changes: 15 additions & 0 deletions nestjs/src/todo/todo.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { TodoService } from './todo.service';
import { TodoController } from './todo.controller';
import { Mongoose } from 'mongoose';
import { MongooseModule, Schema } from '@nestjs/mongoose';
import { TodoSchema, Todo } from './schemas/schema';

@Module({
providers: [TodoService],
controllers: [TodoController],
imports: [
MongooseModule.forFeature([{ name: Todo.name, schema: TodoSchema }]),
],
})
export class TodoModule {}
18 changes: 18 additions & 0 deletions nestjs/src/todo/todo.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { TodoService } from './todo.service';

describe('TodoService', () => {
let service: TodoService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [TodoService],
}).compile();

service = module.get<TodoService>(TodoService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});
});
36 changes: 36 additions & 0 deletions nestjs/src/todo/todo.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Todo, TodoDocument } from './schemas/schema';
import { CreateTodoDto } from './dto/create-todo.dto';
import { UpdateTodoDto } from './dto/update-todo.dto';

@Injectable()
export class TodoService {
constructor(
@InjectModel(Todo.name) private readonly model: Model<TodoDocument>,
) {}

async findAll(): Promise<Todo[]> {
return await this.model.find().exec();
}

async findOne(id: string): Promise<Todo> {
return await this.model.findById(id).exec();
}

async create(createTodoDto: CreateTodoDto): Promise<Todo> {
return await new this.model({
...createTodoDto,
createdAt: new Date(),
}).save();
}

async update(id: string, updateToDto: UpdateTodoDto): Promise<Todo> {
return await this.model.findByIdAndUpdate(id, updateToDto).exec();
}

async delete(id: string): Promise<Todo> {
return await this.model.findByIdAndDelete(id).exec();
}
}

0 comments on commit 8688020

Please sign in to comment.